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
int *vetand not with aint vect[MAX_NUM_OF_NUMS]what can I do? I usereallocto allocate the exact size of memory for contain the numbers.*vet = (int *) realloc (*vet, (i+1) * sizeof(int) );isn't correct?char buff[10];, at leastchar buff[13];for "-2147483648\n" or 2x that for growth.or 2x that for growth.