我在使用一个函数在另一个函数中分配数组时遇到问题。这是导致问题的部分:
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()
函数,甚至会发生变化。
最佳答案
在您的 array_allocator()
函数中,您使用的是复合文字。
关于复合文字的用法,引用C11
标准,章节§6.5.2.5,(强调我的)
[...] If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.
因此,一旦您的函数返回,复合文字就不再存在。因此,在 some_function()
中取消引用 a
又是 UB。
解决方案:您可能希望通过 malloc()
或 family 使用动态内存分配。动态分配内存的生命周期保持有效,除非使用 free()
调用解除分配(或者,为了挑剔,直到程序终止,以较早者为准),因此即使在函数返回之后,您也可以使用相同的。
关于c - 在C中的其他函数中分配数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31863752/