且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

插入排序段错误

更新时间:2023-11-23 15:51:58

在你的下面code,你不要理会内存溢出。

 而(FP!= NULL){
        的fscanf(FP,%D,温度);
        排序[I] =(int)的温度;
        我++;
    }

您分配的内存大小的 INT 的。如果文件较大(超过分配的内存大小),那么你的code将访问的内存超出了分配之一。因此,这可能会导致问题

I have two global Variables COUNT=0; and SIGN=0; Then I #define SIZE 100

I keep getting a seg fault in my code but I'm not too sure where, if you guys could help pin it down for me I'd appreciate it.

It is supposed to print out the total number of assignments that go on while it inserts data read in from a txt doc. I'm not sure if I am understanding what an assignment is actually but this is my go out of it.

void insert(int x[], int n){
int key,y,z;
COUNT++;
    for(z=1; z<n-1; z++){
        key=x[z];
        SIGN++;
        for(y=(z-1); y<0||key>=x[y]; y--){
            x[y+1]=x[y];
            SIGN++;
        }
        x[y+1]=KEY;
    }
int main(){
    FILE *fp;
    fp=fopen("data.txt","r");
    int #temp;
    int i=0;
    int *sort=NULL;
    sort=(int *)malloc(SIZE*sizeof(sort));
    while(fp!=NULL){
        fscanf(fp, "%d", temp);
        sort[i]=(int)temp;
        i++;
    }
    insert(sort, SIZE);
    printf("number of Assignments=%d", SIGN);
    return 0;
}

In your below code,you not bother about the memory overflow.

while(fp!=NULL){
        fscanf(fp, "%d", temp);
        sort[i]=(int)temp;
        i++;
    }

Your allocated memory is SIZEint. If the file size is large(exceeds allocated memory size), then your code will access the memory beyond the allocated one. So this may cause the problem