使用函数在另一个函数中分配数组时遇到问题。这是导致问题的部分:
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)
printf()
不知何故,数组分配后的值变得随机,如果我在打印数组值之前添加一些函数,甚至会改变some_function()
。