0
#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");
        }
    }
}

I run the program this way: ./test_ordina_array.exe 12 TC4_input.txt TC4_oracle.txt TC4_output.txt but it gives me segmentation fault.

"TC4_output.txt" is created by the program while the other two files already exist.

This are the functions used:

    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;
}

They are contained in "vettore.c" and "vettore.h" contains their prototypes.

The program has to order in ascending order the elements contained in the first txt file and write them in the output file.

user11006304
  • 127
  • 7

1 Answers1

3

You have problem when using finput_array

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

Please replace by

finput_array(argv[2], a, &n);
Loc Tran
  • 1,170
  • 7
  • 15