我对 C 很陌生,我刚刚开始学习。如果这个问题看起来有点愚蠢,我深表歉意。
有人可以解释一下为什么这不起作用吗?有什么办法可以完成这样的事情吗? 非常感谢!
struct test{
int arr[10];
};
void foo(struct test t){
t.arr[0] = 1;
}
int main() {
struct test t = {malloc(10*sizeof(int))};
foo(t);
printf("%d", t.arr[0]);
}
我不确定为什么 t.arr[0] 没有分配给 1。
您需要将指向结构体的指针传递给函数 foo() 以允许 foo() 更新结构体 t。我已经在不同的地方更新了您的代码并添加了评论。请注意,由于其声明方式,结构 t 不需要 malloc()。如果您声明了一个指向 struct t 的指针,那么是的,您将需要 malloc()。
可以在这里获取可运行的代码。
#include <stdlib.h>
#include <stdio.h>
struct test{
int arr[10];
};
void foo(struct test *t){ /* updated */
t->arr[0] = 1; /* updated */
}
int main() {
struct test t; /*updated -- this declaration already allocates space for the array in t */
foo(&t); /* updated */
printf("t.arr[0] = %d\nsizeof(t) = %d\n", t.arr[0], sizeof(t));
}
输出:
t.arr[0] = 1
sizeof(t) = 40
C 是一种完全按值传递的语言。
foo
接收其参数的按字节副本,即使对于结构也是如此。修改 t
中的局部变量 foo
不会修改 t
中的变量 main
。
每当为
int arr[10];
分配内存时,结构成员 int
就会自动分配为十个 struct test
的数组。您无需单独分配。
struct test t = {malloc(10*sizeof(int))};
显然是错误的,导致
gcc
报告以下诊断:
foo.c: In function ‘main’:
foo.c:13:22: warning: initialization of ‘int’ from ‘void *’ makes integer from pointer without a cast [-Wint-conversion]
13 | struct test t = {malloc(10*sizeof(int))};
| ^~~~~~
foo.c:13:22: note: (near initialization for ‘t.arr[0]’)
foo.c:13:21: warning: missing braces around initializer [-Wmissing-braces]
13 | struct test t = {malloc(10*sizeof(int))};
| ^
|
传递指针值允许您取消引用该指针,并对它指向的对象进行修改:
#include <stdio.h>
#include <stdlib.h>
struct test{
int arr[10];
};
void foo(struct test *t){
t->arr[0] = 1;
}
int main() {
struct test t = { 0 };
foo(&t);
printf("%d\n", t.arr[0]);
}
1