我制作了一个示例程序来说明问题。在test
我分配内存foo
以存储两个整数。然后,我将每个这些整数设置为一个值,然后打印它们。非常简单,除了我只能在in内进行赋值给整数-当在in内进行赋值main
时将不起作用test
。
此代码有效:
#include <stdio.h>
#include <stdlib.h>
void test(int **foo) {
*foo = malloc(2 * sizeof(int));
}
int main() {
int *foo;
test(&foo);
foo[0] = 4; // <---
foo[1] = 3; // <---
printf("foo[0]: %d\n", foo[0]);
printf("foo[1]: %d\n", foo[1]);
return 0;
}
输出:
foo[0]: 4
foo[1]: 3
这段代码没有:
#include <stdio.h>
#include <stdlib.h>
void test(int **foo) {
*foo = malloc(2 * sizeof(int)); // 3.
*foo[0] = 4; // 4. <---
*foo[1] = 3; // 5. <---
}
int main() {
int *foo; // 1.
test(&foo); // 2.
printf("foo[0]: %d\n", foo[0]);
printf("foo[1]: %d\n", foo[1]);
return 0;
}
输出:
foo[0]: 4 // This is only 4 because it was already
// 4 from running the previous example
foo[1]: 5308612 // And this is obviously garbage
发生什么了?这个答案非常有帮助(或者我认为至少是这样),但是它并没有解决为什么分配工作起作用的问题,main
但是没有解决test
。
这是我对第二个示例中的代码应如何工作的理解(我在代码中添加了脚注以指示我在此处引用的行):
该程序从开始main
。我创建一个整数点foo
,在(为了简单起见)address处分配了一个4字节的内存块1000
。
我发送了foo
对该函数的引用test
。因此,将其1000
作为其参数传递。
为分配了一个大小为两个整数(8个字节)的内存块foo
。
4
存储在地址 1000
3
存储在地址 1004
那么,我的误解是什么,以及如何在第二个示例中修复代码,以便可以foo
在test
而不是中进行初始化main
?
谢谢!
优先!
你需要:
(*foo)[0] = 4; // 4. <---
(*foo)[1] = 3; // 5. <---
没有括号,*foo[0]
is *(foo[0])
,实际上与相同(*foo)[0]
,但是*(foo[1])
写了who-knows-where。该*
运营商结合不太紧密比[]
运营商做,所以你必须使用括号。
char *arr[]; // array of pointers to char
char (*arr)[]; // pointer to array of char
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句