【发布时间】:2015-08-06 18:56:20
【问题描述】:
我在使用一个函数在另一个函数中分配数组时遇到问题。这是导致问题的部分:
void
array_allocator(int method, int** a, int** b){
if (method == 0)
{
(*a) = (int[5]) {0, 1, 2, 3, 4};
(*b) = (int[5]) {5, 6, 7, 8, 9};
printf ("in array_allocator\n");
printf ("a = (%d, %d, %d, %d, %d)\n",(*a)[0],(*a)[1],(*a)[2],(*a)[3],(*a)[4]);
printf ("b = (%d, %d, %d, %d, %d)\n",(*b)[0],(*b)[1],(*b)[2],(*b)[3],(*b)[4]);
}
else printf("unknown method\n");
}
void
some_function (int method){
int *a, *b;
array_allocator(method, &a, &b);
printf ("in some_function\n");
printf ("a = (%d, %d, %d, %d, %d)\n",a[0],a[1],a[2],a[3],a[4]);
printf ("b = (%d, %d, %d, %d, %d)\n",b[0],b[1],b[2],b[3],b[4]);
}
int main()
{
int method = 0;
some_function(method);
return 0;
}
使用 gcc 编译并执行后,我得到了输出:
in array_allocator
a = (0, 1, 2, 3, 4)
b = (5, 6, 7, 8, 9)
in some_function
a = (10, 0, 4196346, 0, 1448083200)
b = (-730692608, 32637, 16, 0, 4196346)
不知何故,数组分配后的值变得随机,如果我在some_function()打印数组值之前添加一些printf()函数,甚至会改变。
【问题讨论】:
-
你实际上并没有分配。你可能想要
malloc。更高级的可能性是划分现有块(甚至可能是静态/全局内存)并将其称为“已分配”,但您不能像现在这样使用堆栈内存。我推荐malloc或操作系统调用来获取内存。
标签: c arrays pointers compound-literals