您需要将指向 struct 的指针传递给函数foo()以允许foo()更新 struct t.我已经在不同的地方用注释更新了您的代码.还请注意, struct t不需要Malloc(),因为它的声明方式...操作系统将为该 struct 预留堆栈空间.如果您只声明了一个 struct 类型的指针,那么是的,您将需要Malloc().
可运行代码可用here.
#include <stdlib.h>
#include <stdio.h>
struct test{
int arr[10];
};
void foo(struct test *t){ /* updated: pointer of type struct t */
t->arr[0] = 1; /* updated. Access pointer struct members like this ( -> ) -- not the dot syntax */
}
int main() {
struct test t; /*updated -- this declaration already allocates space for the array in t -- see output from printf() */
foo(&t); /* updated -- foo() needs a pointer to the struct. So we pass the address of t (&t) */
printf("t.arr[0] = %d\nsizeof(t) = %d\n", t.arr[0], sizeof(t));
}
输出:
t.arr[0] = 1 /* It works! */
sizeof(t) = 40 /* See? 40 bytes allocated already (on my platform). */