Kate Lee
Kate Lee

Reputation: 79

I can't store a string of characters in a node of linked list

I'm doing my coursework regarding airport simulation and I'm having some troubles trying to store information in the character array part.

I am supposed to type in a string of character and it will store in the planeName part of the node but it can't seem to work. My int main() is pretty much empty now because I didn't want to continue coding with incorrect functions.

Below are my codes:

struct node {
    char planeName[5];
    int planeNumber;
    struct node* next;
}; 

struct node* front = NULL;
struct node* rear = NULL;

void Enqueue(char name[5], int x);

int main() {

}

void Enqueue(char name[5], int x){

    struct node* temp = (struct node*)malloc(sizeof(struct node));

    temp -> planeName = name; 
    temp -> planeNumber = x;
    temp -> next = NULL;

    if (front == NULL && rear == NULL)
        front = rear = temp;
    rear -> next = temp; //set address of rear to address of temp
    rear = temp; //set rear to point to temp

    return;
}

This is the error message in the line containing: temp -> planeName = name

This is the part where error message pops up and I have no clue why is this happening.

Can someone please help and ask more questions me if my question is not clear enough?

Upvotes: 4

Views: 1100

Answers (3)

Ziezi
Ziezi

Reputation: 6467

The error comes from the fact that you are performing a shallow copy by copying the name of your array planeName.

If you want to copy your array you need to copy each and every element of it, this is done easier if the last element of your array contains a special character indicating its end, for example the character \0.

An array containing as its last character, the \0 is called: null terminated. There are a lot of functions that perform operations on null terminated arrays. The one that you need is:

char * strcpy ( char * destination, const char * source );

which will copy all of the element of the null terminated array passed as source to destination. In your case it will look like this:

strcpy(temp -> planeName,name);

Here is a brief info about strcpy().

Upvotes: 1

ameyCU
ameyCU

Reputation: 16607

temp -> planeName = name;

You can't assign to an array. Array cannot be used as lvalue. Use strcpy instead-

strcpy(temp -> planeName,name);

Note- But make sure your char arrays are nul terminated before passing them to strcpy.

Upvotes: 5

Scott Hunter
Scott Hunter

Reputation: 49803

Your strings are arrays of characters, so you have to copy the individual elements. Fortunately, there are functions (like strcpy) written to do just that.

Upvotes: 2

Related Questions