正如您在下面的代码中看到的,我尝试打印在不同函数中创建的数组。与我的预期相比,输出的数字完全不同:设置了 0 - 20 之间的数字,但我得到了一些负值。
所以我的问题是为什么会发生这种情况?如果可能的话如何修复它?
#include <stdio.h>
#include <time.h>
#define LEN 10
int* creatingArray();
void printingArray(int* array);
int main(void)
{
int* pointer_array = creatingArray();
printingArray(pointer_array);
getchar();
return 0;
}
int* creatingArray()
{
srand(time(NULL));
int array[LEN] = { 0 };
int* i = 0;
for (i = array; i < array + LEN; i++)
{
*i = rand() % 20;
}
return array;
}
void printingArray(int* array)
{
int* i = 0;
for (i = array; i < array + LEN; i++)
{
printf("\n%d\n", *i);
}
}
最佳答案
注意这段代码:
int* creatingArray()
{
// stuff
int array[LEN] = { 0 };
// more stuff
return array;
}
array
是一个局部变量,因此当函数返回时它会被销毁。然后你就有了一个指向被破坏的变量的指针。它所在的空间(很可能)将继续保存您放在那里的数据 - 直到内存被重新用于其他用途并被覆盖。
and how to fix it if it eve/n possible?
几个选项:
将
array
设为static
变量。那么当函数返回时它就不会被销毁。 (这也意味着每次调用creatingArray
时,它都会使用相同的数组
,而不是新的)使
数组
全局化。将
array
移动到main
,并将指向它的指针传递到creatingArray
,而不是让creatingArray
返回一个。然后,由于它是main
中的局部变量,因此只有在main
返回时才会被销毁。使用
malloc
分配一些在函数返回时不会自动清理的空间。
关于c - 打印在另一个带有指针的函数中设置的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49545181/