简体   繁体   中英

How to scanf strings to array of structs?

I'm trying to create a array of structs and I'm reading the elements of structs from a .txt file. When I'm try to scanf a string from the file my program stops and while debugging codeblocks says "Program received signal SIGSEGV, Segmentation fault.". I'm trying to read the strings from the file and assign them to my structs. What should I do?

My .txt file is below:

H 1 1 MILK White liquid produced by the mammals
H 2 1 IN Used to indicate inclusion within space, a place, or limits
H 3 3 BUS A road vehicle designed to carry many passengers
H 5 3 DAN The name of a famous author whose surname is Brown
V 1 1 MIND A set of cognitive faculties, e.g. consciousness, perception, etc.
V 3 3 BAD Opposite of good
V 2 5 ISBN International Standard Book Number

and my loadTextFile function to assign these values to my struct array is below:

Word_t* loadTextFile(FILE* myfile, int nrWords)
{
  Word_t* temp;
  temp=malloc(sizeof(Word_t)*nrWords);
  temp->word=malloc(MAX_WORD_LENGTH);
  temp->clues=malloc(MAX_CLUES_LENGTH);

  for(int count=0;count<nrWords;count++)
  {
    fscanf(myfile," %c %d %d %s %[^\n]%*c", &temp[count].direction,&temp[count].x, &temp[count].y, temp[count].word, temp[count].clues);
  }
  printf("ELEMENTS");
  for(int i=0;i<nrWords;i++)
  {
    printf("%c %d %d %s %s\n", temp[i].direction, temp[i].x, temp[i].y,temp[i].word, temp[i].clues);
  }

  return temp;
  }

I want to make my output look like the txt file.

You have posted small part of your code, but I think your problem source is here:

temp->word=malloc(MAX_WORD_LENGTH);
temp->clues=malloc(MAX_CLUES_LENGTH);

You practically only allocating memory for 1st element or in other words temp[0] , but you need to do this for all of your array members. Hence, your code should be something like this:

for(int count=0;count<nrWords;count++)
  {
    temp[count]->word=malloc(MAX_WORD_LENGTH);
    temp[count]->clues=malloc(MAX_CLUES_LENGTH);
    fscanf(myfile," %c %d %d %s %[^\n]%*c", &temp[count].direction,&temp[count].x, &temp[count].y, temp[count].word, temp[count].clues);
  }

I give a small hand for this bug, But remember to learn utilize debuggers for finding these small bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM