Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 条件下的分段故障_Arrays_Segmentation Fault_Primes - Fatal编程技术网

Arrays 条件下的分段故障

Arrays 条件下的分段故障,arrays,segmentation-fault,primes,Arrays,Segmentation Fault,Primes,我的程序的目的是找到由用户输入指示的素数。我设置了一个数组来存储找到的素数。当p(被测整数)增加且测试重新启动时,只需除以数组中的元素即可保存处理。它在44030黄金时段前都很有效。我正在使用GCC进行编译。为什么它会给我一个分段错误 //Prime Finder #include <stdio.h> #include <stdlib.h> int main () { int i=4; int p=7; int j=1; int cap; printf("\nWhich

我的程序的目的是找到由用户输入指示的素数。我设置了一个数组来存储找到的素数。当p(被测整数)增加且测试重新启动时,只需除以数组中的元素即可保存处理。它在44030黄金时段前都很有效。我正在使用GCC进行编译。为什么它会给我一个分段错误

 //Prime Finder
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i=4;
int p=7;
int j=1;
int cap;
printf("\nWhich prime number would you like to see? ");
scanf("%i",&cap);
long *array=malloc(cap);
array[0]=1;
array[1]=2;
array[2]=3;
array[3]=5;
while(i<=cap)
{
if (array[j]>=p/2) // if true then p is prime
{
    j=1;
    array[i]=p;
    p++;
    i++;
}
else if (p%array[j]==0) // if true then p is not prime
{
    p++;
    j=1;
}
else // in this case p is still under test
    j++;
}
printf("\nHere it is! %i\n\n",array[cap]);
return 0;
}
//素数查找器
#包括
#包括
int main()
{
int i=4;
int p=7;
int j=1;
int cap;
printf(“\n您希望看到哪个素数?”);
scanf(“%i”和“cap”);
长*数组=malloc(cap);
数组[0]=1;
数组[1]=2;
数组[2]=3;
数组[3]=5;
while(i=p/2)//如果为真,那么p是素数
{
j=1;
数组[i]=p;
p++;
i++;
}
else如果(p%array[j]==0)//如果为true,则p不是素数
{
p++;
j=1;
}
否则//在本例中,p仍在测试中
j++;
}
printf(“\n就是它!%i\n\n”,数组[cap]);
返回0;
}

您在
malloc()调用中分配的是
cap
字节,而不是
cap*sizeof(long)
字节。所以你正在覆盖内存的其他部分;具体时间取决于您提供给cap的值。

是否可能特定素数刚好超过int的存储长度?(毫无阻碍地回答)我不这么认为。Int在2147483647之前是良好的。44030素数是532691。好的,不用担心。只是一个想法:)我感觉到了。我现在就接受任何建议,因为我被难住了。就是那个!修好了!谢谢D