Search code examples
clinked-listc-strings

Storing a string in struct via an argument to a function


I'm struggling to figure out how to pass a string into a function and then how to store it in struct via pointer. I want to create a linked list where each node contains a node name(string) and data(integer) representing the weight required to reach that node.

The structure representing the node is as follows:

struct ListNode
{
    // The energy required to reach in this node
    int data;
    // The name of the node
    char location[20];

    // And the nodes along side this one
    struct ListNode* next;
    struct ListNode* prev;
};

The following function generates a node and sets its next and previous pointers:

// Allocate a new listNode with the provided value
struct ListNode* listNodeConstructor(int value, char *city)
{
    struct ListNode* newNode;

    // Reserve memory for a node
    newNode = malloc(sizeof(struct ListNode));

    // Set its values
    newNode->data = value;
    newNode->name = strdup(city); /* This is how I've tried to implement it but it causes an error */
    newNode->next = NULL;
    newNode->prev = NULL;

    // And return it
    return newNode;
}

If anyone can show me how to correctly store the string in the node struct, I would be eternally grateful.


Solution

  • strdup() copies a string to a newly malloced place in the heap and returns a pointer to the new string.

    Note that you also need to free it.

    The problem is, that the string you want to set is part of the structure and not just a pointer you can set.

    You have two options:

    • Use strcpy(newNode->name,city); instead of newNode->name = strdup(city);. This copies the city string to newNode but you need to assure that city has a \0 until newNode->name overflows.

    • change name to be just a pointer and free it when you free the node. You can use strdup in that case. (Change char location[20]; to char *location;