我的一个同学给我发了一个代码,问它有什么问题。是这样的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *d_array, number, divisor_count, i, size = 1;
char answer;
d_array = (int*) malloc(size * sizeof(int));
do
{
printf("\nEnter a number: ");
scanf("%d", &number);
divisor_count = 0;
for(i = 2; i < number; i++)
if (number % i == 0) divisor_count++;
if(divisor_count == 0)
{
realloc(d_array,(size + 1) * sizeof(int));
d_array[size - 1] = number;
size++;
}
printf("\nIs there another number? y/n ");
getchar();
answer = getchar();
} while (answer == 'y');
for(i = 0; i < size - 1; i++)
printf("\n%d", d_array[i]);
return 0;
}
它应该从用户那里获取数字并保留主要的数字并最终打印出来。我电脑上的输出是这样的:
Enter a number: 3
Is there another number? y/n y
Enter a number: 5
Is there another number? y/n y
Enter a number: 8
Is there another number? y/n y
Enter a number: 7
Is there another number? y/n y
Enter a number: 2
Is there another number? y/n n
4072680
5
7
2
代码中还有其他内容,但最大的问题显然是没有分配 realloc() 的返回值。但奇怪的是,这是我的问题,为什么这段代码显示第一个质数错误而其他正确?动态数组的地址可能会改变,但为什么第二个和其余的都是正确的而不是第一个呢?
编辑:好的,我问这个的原因是试图理解 realloc() 在这段代码中的行为,如果你有好的资源请分享。重新分配内存时(释放旧内存时), realloc() 是否会更改旧内存位置的内容?