我的代码在这里遇到了一个非常奇怪的问题。当我使用手动打印语句输出 int *primesArr 的值时,它(看似)有效,但如果我尝试使用 for 循环这样做,它会失败。我通过 gdb 运行它,发现它在我将数组中的下一个单元格设置为值“k”的地方崩溃,这仅在数字为素数时发生。第一次迭代成功(即 2 设置为 primesArr[0]),然后在尝试增加数组时程序 Segfaults。但这仅在使用 for 循环时发生。当我创建单独的打印语句时,我的程序按预期工作。我不确定在使用 for 循环时如何/为什么要访问尚未分配的内存。我确定我在某个地方犯了一些业余错误,这可能与我传递指针的方式有关...... 但我无法确定它的确切根源。我将不胜感激,并提前感谢您。
#include<stdio.h>
int genPrimes(int seed, int *test){
int inNumPrimes=0;
for(int k=0; k<=seed; k++){//k is number being checked for primeness
int cnt=0;
for(int i=1; i<=k; i++){//'i' is num 'k' is divided by
if(k%i == 0){
cnt++;
if(cnt > 2){
break;
}
}else{
}
}
if(cnt == 2){
printf("%i IS PRIME\n",k);
*test=k;
test++;//according to gdb, the problem is somewhere between here
inNumPrimes++;//and here. I'd wager I messed up my pointer somehow
}
//printf("%i\n",k);
}
return inNumPrimes;
}
int main(){
int outNumPrimes=0;
int *primesArr;
int n = 0;
n=20;
outNumPrimes=genPrimes(n, primesArr);
printf("Congratulations! There are %i Prime Numbers.\n",outNumPrimes);
//If you print using this for loop, the SEGFAULT occurs. Note that it does not matter how high the limit is; its been set to many values other than 5. It will eventually be set to 'outNumPrimes'
//for(int a=0; a<5; a++){
//printf("%i\n",primesArr[a]);
//}
//If you print the array elements individually, the correct value--a prime number--is printed. No SEGFAULT.
printf("%i\n",primesArr[0]);
printf("%i\n",primesArr[1]);
printf("%i\n",primesArr[2]);
printf("%i\n",primesArr[3]);
printf("%i\n",primesArr[4]);
printf("%i\n",primesArr[5]);
printf("%i\n",primesArr[6]);
printf("%i\n",primesArr[7]);
//
return 0;
}
带有手动语句的输出:
$ ./a.out
2 IS PRIME
3 IS PRIME
5 IS PRIME
7 IS PRIME
11 IS PRIME
13 IS PRIME
17 IS PRIME
19 IS PRIME
Congratulations! There are 8 Prime Numbers.
2
3
5
7
11
13
17
19
现在使用 for 循环:
$ ./a.out
2 IS PRIME
Segmentation fault