我在第二个函数中的realloc语句一直工作到一个点,然后指针似乎突然指向随机内存。有人可以解释一下我如何解决这个问题吗?看看输出,可能会节省一些时间。谢谢。
int main()
{
int testCases, i, n;
int* primeArray;
int* size;
primeArray = malloc(sizeof(int));
primeArray[0] = 2;
size = 1;
int number = 2;
while(number < 1000){
number = nextPrime(number, primeArray, &size);
printf("Prime Array at %d is %d, size is %d, number is %d n", 0, primeArray[0], size, number);
}
scanf("%d", &testCases);
for(i = 0; i < testCases; i++){
scanf("%d", n);
}
free(primeArray);
free(size);
return 0;
}
第二个功能:
int nextPrime(int number, int* primeArray, int* size){
int foundPrime = 0, num = number, i;
while(!foundPrime){
num++;
int allNums = 0;
//printf("Size: %d n", *size);
for(i = 0; i < *size; i++){
//printf("%d mod %d n", num, primeArray[i]);
if(num % primeArray[i] != 0){
allNums += 0;
}
else {
allNums = 1;
break;
}
}
if(allNums == 0){
*size+=1;
//printf("Size: %d n", *size);
foundPrime = 1;
primeArray = realloc(primeArray, *size * sizeof(int) );
primeArray[*size-1] = num;
//printf("%d n", primeArray[*size-1]);
return num;
}
}
}
输出:
Prime Array at 0 is 2, size is 2, number is 3
Prime Array at 0 is 2, size is 3, number is 5
Prime Array at 0 is 2, size is 4, number is 7
...
Prime Array at 0 is 2, size is 94, number is 491
Prime Array at 0 is 2, size is 95, number is 499
Prime Array at 0 is 2, size is 96, number is 503
Prime Array at 0 is 16852008, size is 97, number is 509
primeArray
,即使它是一个指针,也会通过值传递给您的nextPrime
函数。 因此,如果realloc
更改指针值(它可以并且经常会),main
不会在返回时将该值反映回nextPrime
。快速解决方法是更改nextPrime
,使其使用指向指针参数的指针,而不仅仅是数组指针。
下面是一个快速修复,我修改了nextPrime
的函数签名,并将代码添加到函数的开头和结尾。
int nextPrime(int number, int** ptrToPrimeArray, int* size){
int* primeArray = *ptrToPrimeArray; // primeArray is the deferenced value of ptrToPrimeArray
int foundPrime = 0, num = number, i;
while(!foundPrime){
num++;
int allNums = 0;
//printf("Size: %d n", *size);
for(i = 0; i < *size; i++){
//printf("%d mod %d n", num, primeArray[i]);
if(num % primeArray[i] != 0){
allNums += 0;
}
else {
allNums = 1;
break;
}
}
if(allNums == 0){
*size+=1;
//printf("Size: %d n", *size);
foundPrime = 1;
primeArray = realloc(primeArray, *size * sizeof(int) );
primeArray[*size-1] = num;
//printf("%d n", primeArray[*size-1]);
*ptrToPrimeArray = primeArray; // return the changed value of primeArray back to the caller
return num;
}
}
}
然后在main
中调用它,如下所示:
number = nextPrime(number, &primeArray, &size);
您将 realloc()
返回的值分配给局部变量,当函数返回时,该变量当然会消失nextPrime()
。main()
中primeArray
的值永远不会改变。