我試圖從文件FILE1中讀取N個數字到數組中 然後對這些數字進行排序;然後在數組中搜索數字(每行1個,在FILE2中給出)對於每個輸入數字。在動態數組中搜索
但是,當我運行此代碼時,它給出了「分段失敗」。請幫我改正這段代碼。 繼承人我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include<string.h>
int size=32;
int main(int argc,char* argv[])
{
FILE *fp1=fopen("myFile1.txt","r");
if (fp1 == NULL)
{
printf("cannot open this file");
exit(0);
}
FILE *fp2 = fopen("test1.txt", "w");
if (fp2 == NULL)
{
printf("cannot open this file");
exit(0);
}
FILE *fp3=fopen("myFile2.txt","r");
if (fp3 == NULL)
{
printf("cannot open this file");
exit(0);
}
int i=0,k,j,l,num,temp,m,c,d,Y,l1,u,mid,X,Z;
int *B;
int *C;
int n;
B= malloc(sizeof(int)*size);
while(fscanf(fp1,"%d",&num)==1)
{
if(i<size)
{
B[i]=num;
i++;
}
else
{
C = malloc(sizeof(int)*2*size);
for(m=0;m<size;m++)
{
C[m]=B[m];
}
free(B);
size=size*2;
B=&C[0];
}
}
for(j=0;j<size;j++)
{
for(l=0;l<size-1;l++)
{
if(B[l]>B[l+1])
{
temp=B[l];
B[l]=B[l+1];
B[l+1]=temp;
}
}
}
for(j=0;j<size;j++)
fprintf(fp2,"%d ",B[j]);
Y=0;
while(fscanf(fp3,"%d",&X)==1)
{
for(i=0;i<n;i++)
{
if(B[i]==X)
{
Y=1;
Z=i+1;
break;
}
else
{
if(X<B[i])
{
Z=i+1;
Y=0;
break;
}
if(X>B[n-1])
{
Z=n;
Y=0;
break;
}
}
}
if(Y==1)
printf("number %d found at %d",X,Z);
else
printf("number not found");
}
return 0;
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
我不能確定,但它看起來像你可能試圖訪問'B'後稱爲'免費(乙);'。您可以使用GDB找出哪一行導致段錯誤;使用'gcc -g main.c -o program'進行編譯,然後使用'gdb myprogram'將你的程序加載到GDB中。在GDB提示符下,執行'run'。在seg故障類型'bt'後,您將看到導致seg故障的線路的呼叫跟蹤。 –