尝试将指针指向函数中的指针时出现段错误 [英] Segfault when trying to index pointer to pointers in function
问题描述
我正在尝试使用数组(malloc-ed),即自定义结构的arr
.该数组通过引用传递给函数.每当我在运行时尝试在函数中索引除arr[0]
以外的任何内容时,都会遇到段错误(例如(*arr[1])->i = 3;
).为什么会这样?
I'm trying to do something with an array (malloc-ed), namely arr
of a custom struct. The array is passed by reference to a function. I get a segfault whenever I tried to index anything other than arr[0]
in the function at runtime (e.g (*arr[1])->i = 3;
). Why is this happening?
完整的源代码是:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
typedef struct{
int i;
float f;
}foo;
void doSomething(foo ***arr);
int main()
{
foo **arr = (foo**) malloc (SIZE * sizeof(foo*));
int i;
for(i = 0; i < SIZE; i++)
arr[i] = (foo*)malloc(sizeof(foo));
arr[1]->i = 1;
printf("Before %d\n",arr[1]->i );
doSomething(&arr);
printf("After %d\n",arr[1]->i );
return 0;
}
void doSomething(foo ***arr)
{
(*arr[1])->i = 3;
}
推荐答案
您的问题是那行
(*arr[1])->i = 3;
因为下标运算符的评估位于之前,因此,它等于取消引用的评估以下:
Because the subscripting operator's evaluation precedes the dereferencing's evaluation it is equivalent to the following:
(*(arr[1]))->i = 3;
这显然是错误的.您需要
This is obviously wrong. You need
(*arr)[1]->i = 3;
因此.
注意:
- 不转换
malloc
的结果 - 添加
#include <stdlib.h>
来解决警告 - 无需添加额外的间接级别(
foo***
指向foo**
);只需按值复制 -
(除了大写字母外),对于您而言,一个好的旧一维数组实际上应该足够了
- do not cast the result of
malloc
- add
#include <stdlib.h>
to resolve the warning - adding an extra level of indirection (
foo***
pointing tofoo**
) is unnecessary; just copy by value (in addition to the upper note) a good old 1D array should actually be sufficient in your case
在malloc
这篇关于尝试将指针指向函数中的指针时出现段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!