1. Engineering
  2. Computer Science
  3. c programming problem 3 double pointers a double pointer or...

Question: c programming problem 3 double pointers a double pointer or...

Question details

c programming

Problem 3 [Double Pointers]

A double pointer or a pointer-to-pointer is basically a pointer that pointers to another pointer. In other words, it store an address, which you look up, and you will find another address that points to another memory location.

If you go online to search for linked-list examples, you will often find double pointers. You must feel very frustrated in the last lab!

Below you will find a incomplete program on linked list that utilizes double pointer.

Please complete the function insertToStart so that we will have the right output. Do not change the main program or the method parameters and return types. You can look at createList as an example on using the double pointer.

#include <stdio.h>

#include <stdlib.h> // <--- remember this

typedef struct node {

    int data; // just generic, meaningless data!

    struct node *next;

} Node;

void createList(Node **refToListHead, int firstData) {

    // in this func, we create the first node to the list

    // and put the firstData inside the first node;

    // the listHead is passed in by reference as refToListHead

    // and will be updated upon function end

   

    printf("creating list...\n");

    Node *newNode = malloc(sizeof(Node));

    newNode->data = firstData;

    newNode->next = NULL;

   

    *refToListHead = newNode; // refToListHead points to listHead

    printf("address stored in refToListHead is %p\n",refToListHead);

    printf("address stored in *refToListHead is %p\n",*refToListHead);

   

}

void insertToStart(Node **refToListHead, int dataToInsert) {

    // we will insert the dataToInsert to start of the list

    Node *originalListHead;

    originalListHead = *refToListHead;

   

    // INSERT YOUR CODE HERE!

}

void printList(Node* listHead) {

    printf("printing list: ");

    Node *current = listHead;

    while (current != NULL) {

        printf("%d ",current->data);

        current = current->next;

    }

    printf("\n");

}

int main()

{

    Node *myHead = NULL; // head of the linked list, not really MY HEAD!

    printf("address stored in myHead is %p\n", myHead);

    createList(&myHead, 2018);

    printf("address stored in myHead is %p\n", myHead);

    printList(myHead);

    insertToStart(&myHead, 2020);

    insertToStart(&myHead, 1900);

    printList(myHead);

   

    return 0;

}

The output should look like this, if done correctly (the addresses will be different):

address stored in myHead is (nil)
creating list...
address stored in refToListHead is 0x7fff736240c8
address stored in *refToListHead is 0x10cf020
address stored in myHead is 0x10cf020
printing list: 2018
printing list: 1900 2020 2018

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution