在ac函数中分配一个数组

gui*_*ouz 3 c pointers

我正在尝试在函数内部分配和初始化一个数组,但我似乎无法在返回后获取值.

这是我最近几乎在努力的尝试

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int func(int **thing);

int main() {

 int *thing;

 func(&thing);

 printf("%d %d", thing[0], thing[1]);
}

int func(int **thing) {

 *thing = calloc(2, sizeof(int));

 *thing[0] = 1;
 *thing[1] = 2; 

 printf("func - %d %d \n", *thing[0], *thing[1]);
}
Run Code Online (Sandbox Code Playgroud)

但是在函数外部打印的值是1和0.有很多关于指针的文档,但我没有发现这个特定的案例.关于我做错的任何提示?

Gre*_*ill 6

您可能会发现从函数返回新分配的数组更容易,而不是传递指针指针:

int *func();

int main() {

 int *thing;

 thing = func();

 printf("%d %d", thing[0], thing[1]);
}

int *func() {

 int *thing;

 thing = calloc(2, sizeof(int));

 thing[0] = 1;
 thing[1] = 2; 

 printf("func - %d %d \n", thing[0], thing[1]);

 return thing;
}
Run Code Online (Sandbox Code Playgroud)

你的代码不起作用的原因是因为:

*thing[0]
Run Code Online (Sandbox Code Playgroud)

由于运算符的优先级,您应该使用:

(*thing)[0]
Run Code Online (Sandbox Code Playgroud)


Ben*_*son 5

您的任务的优先级*和优先级.你需要明确括起来像.[]*(thing[0])(*thing)[0]