我卡在那个代码里了 如何为该结构分配内存
typedef struct {
int a, b, c, d;
} FourInts;
void fillArray(int* array, int len) {
printf("Filling an array at address %p with %d "
"values\n", array, len);
for (int i = 0; i < len; ++i) {
array[i] = (i * 3) + 2;
// assert() verifies that the given condition is true
// and exits the program otherwise. This is just a
// "sanity check" to make sure that the line of code
// above is doing what we intend.
assert(array[i] == ( (i * 3) + 2) );
}
printf("Done!\n");
}
/***********from here the problem *******/
struct FourInts *heap_struct_FourInts = (FourInts*) malloc(sizeof( FourInts) * 1);
fillArray(heap_struct_FourInts->*a), 4);
free(heap_struct_FourInts);
编译器给我那个错误
arrays.c:222:43: warning: initialization from incompatible pointer type [enabled by default]
struct FourInts *heap_struct_FourInts = (FourInts*) malloc(sizeof( FourInts) * 1);
^
arrays.c:224:33: error: dereferencing pointer to incomplete type
fillArray(heap_struct_FourInts->a, 4);
^
struct 和 malloc 的代码有什么错误?
最佳答案
下面的函数调用是错误的:
fillArray(heap_struct_FourInts->*a), 4);
a
是一个 int
,而不是指向 int
的指针,因此您不能取消引用它。 (即使它是指向 int
的指针,您的语法也不正确)。
另外,在你的结构中......
typedef struct {
int a, b, c, d;
} FourInts;
...您不是在声明一个包含 4 个 int
的数组,而是四个独立的 int
。如果您希望 a
是一个长度为 4 的 int
数组,您需要像这样声明它:
typedef struct {
int a[4], b, c, d;
} FourInts;
现在你可以这样调用你的函数了:
FourInts *heap_struct_FourInts = malloc(sizeof(*heap_struct_FourInts);
fillArray(heap_struct_FourInts->a), 4);
下面是等价的:
fillArray((*heap_struct_FourInts).a), 4);
关于c - 使用内存分配构造指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24685523/