在c函数中分配数组 [英] allocating an array inside a c function
问题描述
我正在尝试在函数内部分配和初始化数组,但返回后似乎无法获取值.
I'm trying to allocate and initialize an array inside a function, but I can't seem to fetch the values after returning.
这是我最后一次几乎可以正常工作的尝试
This was my last almost-working attempt
#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]);
}
,但函数外部打印的值为1和0. 有很多关于指针的文档,但是我还没有发现涉及此特定案例的内容.关于我在做什么错的任何提示吗?
but the values printed outside the function are 1 and 0. There are lots of documentation on pointers out there, but I haven't found this specific case covered. Any tips on what I'm doing wrong ?
推荐答案
与其传递指针到指针,不如从函数中返回新分配的数组,会更容易:
Rather than passing a pointer-to-pointer, you may find it easier to return the newly allocated array from your function:
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;
}
您的代码不起作用的原因是因为:
The reason your code doesn't work is because of this:
*thing[0]
由于运算符的优先级,您应该使用:
Due to the precedence of operators, you should use:
(*thing)[0]
这篇关于在c函数中分配数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!