0

I use fscanf to read an array of chars from a text file. I would like to add that string to a linked struct, however it gives me an error (expression must be a modifiable value). I'm using structs for the first time, please help!

My struct:

typedef struct animals{
    char name_of_animal[51];
    struct animals *next;
} ANIMALS;

Later, the way I want to add a new element to this linked struct:

{
    char name_of_animal[51];
    /*
     * use fscanf to read into name_of_animal
     */

    ANIMALS* new_animal = (ANIMALS*) malloc(sizeof(ANIMALS)); 
    new_animal->name_of_animal = name_of_animal; 
    new_animal->next = (*pointer_to_pointer_to_beginning); 
    (*pointer_to_pointer_to_beginning) = new_animal; 
}
PiCTo
  • 924
  • 1
  • 11
  • 23

2 Answers2

1

Your problem has nothing to do with structs: you read a string into a char[51] (name_of_animal) and are trying to copy it into another char[51] (new_animal->name_of_animal) by using the assignment operator (=). You can't do that and should instead use strcpy from <string.h>.

PiCTo
  • 924
  • 1
  • 11
  • 23
0

"I would like to add that string to a linked struct, however it gives me an error ("expression must be a modifiable value")"

Regarding adding string to a linked struct, use a function to create a link and update the string member using a string function, rather than the = operator. Eg:

void createNode(struct zvierata** head_ref, char *new_data) 
{ 
    //allocate memory for new node
    struct zvierata *new_node = malloc(sizeof(*new_node)); 
   
    // copy data to member
    //new_node->meno_zvierata = new_data; // '=' does not work with strings
    strcpy(new_node->meno_zvierata,  new_data); 
   
    new_node->next = (*head_ref); 
   
    //finally move the head to point to the new node
    (*head_ref)    = new_node; 
} 

" I'm using structs for the first [time], please help!"

Here are several pages of tutorial on Linked Lists (which is what you are using.)

ryyker
  • 22,849
  • 3
  • 43
  • 87