namarino41
namarino41

Reputation: 123

Printing a linked List only prints most recent data entry in C

I'm printing a linked list after each addition to it. The problem is that it only prints the most recently added node. The user is supposed to enter a string which is used to make a node and then that node is added to the list. Here is the code:

int main() {
    char userChoice = printMenu();
    int setNumber;

    while (userChoice != 'q') {
        printf("set: ");
        scanf("%d", &setNumber);

        Node **nodeArray;
        nodeArray = malloc(10 * sizeof(Node *));

        int i;
        for (i = 0; i < 10; i++) {
            nodeArray[i] = malloc(sizeof(Node));    
        }

        if (userChoice == 'a') 
            add(&nodeArray, setNumber);
        else 
            printf("Please enter a valid menu option.");

        //printf("%s\n", (nodeArray[setNumber]->next)->data);

        userChoice = printMenu();
    }

void add(Node ***nodeArray, int setNumber) {
        char userString[5];
        printf("Please enter some data: ");
        scanf("%s", userString);

        Node *head = *nodeArray[setNumber];     /* head pointer to first element of array (dummy) */
        Node *newNode = malloc(sizeof(Node));   /* new node to be added to array */

        strncpy(newNode->data, userString, sizeof(newNode->data));  /* copies string entered by the user to data field of new node */
        newNode->next = NULL;   /* initializes next field of new node to NULL */

        while (head->next) 
            head = head->next;      /* points head to next element in list */
        head->next = newNode;   /* adds element to list */

        head = *nodeArray[setNumber];   /* points head back to start of list */
        Node *tmp = head;       

        printf("List is: ");
        while (tmp->next) {
            printf("%s", tmp->data);
            tmp = tmp->next;
        }
}

Just as an example, when I enter "one", it prints out "one". Then when I add "two" it only prints out two instead of printing out "one two". What am I doing wrong?

Upvotes: 0

Views: 54

Answers (2)

namarino41
namarino41

Reputation: 123

The problem is that a new block of memory is being created every time you enter into the loop. Cut and paste the code that creates the array outside of the loop and everything should work fine.

Upvotes: 0

Waxrat
Waxrat

Reputation: 2185

This *nodeArray[setNumber] means *(nodeArray[setNumber]) but you seem to mean (*nodeArray)[setNumber]. Or better, don't pass &nodeArray to add(), just pass nodeArray. So:

add(nodeArray, setNumber);
...
void add(Node **nodeArray, int setNumber) {
...
Node *head = nodeArray[setNumber];

Upvotes: 1

Related Questions