0

I have a file with 10 lines, and in each line there is, separated by spaces, a name, an id and an age. Problem is that when reading this file with fgets and sscanf, it returns me a seg fault when trying to read more than 2 lines.

typedef struct Person
{
    char t;
    long i;
    float a;
} Person;



*arrPersons = (Person*)malloc(10 * sizeof(Person));

int assignInputPeople(Person **arrPersons,  FILE *inputPeople)
{
    int counter = 0;
    char fileLine[344];
    long ID;
float ageF;
 while (fgets(fileLine, 344, inputPeople) != NULL)
    {
        sscanf(fileLine, "%s %s %s", arrPersons[counter]->name,&ID)
   
    
}

I created a pointer to pointer for my array so that I can modify it in other functions, like this one above.

MM1
  • 912
  • 1
  • 10
  • 28

1 Answers1

2

If you are passing the address of arrPersons in the main() function as the argument arrPersons of the assignInputPeople() function, arrPersons[counter]->name is wrong because what is pointed at by arrPersons have only room for one elemnet, so it is out-of-range when counter is not 0.

In this case, it should be (*arrPersons)[counter].name.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Where the line `*arrPersons = (Person*)malloc(10 * sizeof(Person))` actually is? – MikeCAT Aug 02 '20 at 10:44
  • 1
    Also what is `capacity`? – MikeCAT Aug 02 '20 at 10:45
  • Just do you know why I have a warning saying that my fields aren't used in my struct ? – MM1 Aug 02 '20 at 11:08
  • It should be because your fields aren't used. – MikeCAT Aug 02 '20 at 11:09
  • But when using sscanf , I use them in order to store the data in the line, like for (*arrPersons)[counter].id , or doesn't it count as accessed ? – MM1 Aug 02 '20 at 11:12
  • Your posted code doesn't contain that. Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – MikeCAT Aug 02 '20 at 11:13
  • [Coundl't reproduce](https://wandbox.org/permlink/ucbSUJNxXp50jBus) after adding some tweaks to make it compile. I'd answer "No" for the question "do you know". – MikeCAT Aug 02 '20 at 11:21