2

I have a file who has num lines: every line contains one number. I want to save every number into a vector *vet. Why this code doesn't work?

Segmentation fault (core dumped)

I think that the error is sscanf in save_numbers function, but I don't know why.

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

/* This function allocate memory
and save numbers into a vector */
int save_numbers (int **vet, int *num)
{
    FILE *fin;
    int i = 0;
    char buff[10];

    if ( !(fin = fopen("numbers.dat", "r")) )
        return 1;

    while ( fgets(buff, sizeof(buff), fin) )
    {
        *vet = (int *) realloc (*vet, (i+1) * sizeof(int) );
        sscanf (buff, "%d", vet[i]);
        i++;
    }

    *num = i;

    return fclose(fin);
}

int main ()
{
    int i, num, *vet = NULL;    

    if ( save_numbers(&vet, &num) )
    {
        perror("numbers.dat");
        exit(1);
    }

    /* print test */
    for (i=0; i<num; i++)
        printf ("%d ", vet[i]);
    printf("\n");

    free(vet);

    return 0;
}

Example of file here: http://pastebin.com/uCa708L0

19
  • 1
    @A Person But if I want to do it with int *vet and not with a int vect[MAX_NUM_OF_NUMS] what can I do? I use realloc to allocate the exact size of memory for contain the numbers. Commented Jan 12, 2014 at 22:48
  • 2
    But why? *vet = (int *) realloc (*vet, (i+1) * sizeof(int) ); isn't correct? Commented Jan 12, 2014 at 23:00
  • 1
    let us continue this discussion in chat Commented Jan 12, 2014 at 23:09
  • 1
    Minor: suggest larger size for char buff[10];, at least char buff[13]; for "-2147483648\n" or 2x that for growth. Commented Jan 13, 2014 at 1:30
  • 1
    @chux.What do you mean with or 2x that for growth. Commented Jan 13, 2014 at 1:32

1 Answer 1

5

change

sscanf (buff, "%d", vet[i]);//vet : int **

to

sscanf (buff, "%d", &(*vet)[i]);
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Thank you very much! Can I ask you if the code in general is good?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.