尝试运行此程序时出现细分错误错误

时间:2019-02-19 14:13:05

标签: c

#include <stdio.h>
#include <stdlib.h>
#include "vettore.h"

int main(int argc, char *argv[]){
    if(argc != 5)
        printf("Incorrect parameters number\n");
    else{
        int n = atoi(argv[1]);
        int *a = (int*) calloc(n, sizeof(int));
        if(a == NULL)
            printf("Unsufficient memory\n");
        else{
            finput_array(argv[2], a, n);
            bubblesort(a, n);
            foutput_array(argv[4], a, n);
            int *oracle = (int*) calloc(n, sizeof(int));
            finput_array(argv[3], oracle, n);

            if(compare_array(a, oracle, n))
                printf("PASS\n");
            else
                printf("FAIL\n");
        }
    }
}

我以这种方式运行程序:./test_ordina_array.exe 12 TC4_input.txt TC4_oracle.txt TC4_output.txt,但它给我分段错误。

该程序创建了“ TC4_output.txt”,而另外两个文件已经存在。

这是使用的功能:

    void bubblesort(int a[], int n){
int i, j;
  for(i = 0 ; i < n - 1; i++)
  {
    for(j = 0 ; j < n - i - 1; j++)
    {
      if (a[j] > a[j+1]) /* For decreasing order use < */
      {
        swap(&a[j], &a[j+1]);
       }
      }
     }
}

void finput_array(char *file_name, int a[], int *n){
    FILE *fd = fopen(file_name, "r");
    if(fd == NULL)
        printf("Errore in apertura del file %s\n", file_name);
    else{
        int i = 0;
        fscanf(fd, "%d", &a[i]);
        while(i<*n && !feof(fd)){
            i++;
            fscanf(fd, "%d", &a[i]);
        }
        fclose(fd);
        if(i<*n)
            *n = i;
    }
}

void foutput_array(char *file_name, int a[], int n){
    int i;
    FILE *fd;

    fd = fopen(file_name, "w");
    if(fd == NULL)
        printf("Errore in apertura del file %s\n", file_name);
    else{
        for(i=0; i<n; i++)  
            fprintf(fd, "%d\n", a[i]);
        fclose(fd);
    }
}

int compare_array(int a[], int b[], int n){
    int i=0;

    while(i<n && a[i] == b[i])
        i++;

    return (i==n) ? 1 : 0;
}

它们包含在“ vettore.c”中,“ vettore.h”包含其原型。

程序必须按升序对第一个txt文件中包含的元素进行排序,然后将它们写入输出文件中。

1 个答案:

答案 0 :(得分:3)

使用finput_array时遇到问题

finput_array(argv[2], a, n);

请替换为

finput_array(argv[2], a, &n);