-1

I honestly don't really understand how this code works. To make it work would I just need to change the type of some of the functions or would I need to change more than that?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct LinkedList{
    int data;
    struct LinkedList* next;
};
int main(){
    struct LinkedList *A = NULL;
    insert(A, 3);
    printList(A);
    return 0;
}
void insert(struct LinkedList *root, int item){
   root=malloc(sizeof(struct LinkedList));
   root->data= item;
   root->next = NULL;
}
void printList(struct LinkedList *head){
    struct LinkedList *temp=head;
    while (temp != NULL){
        printf("%d", temp->data);
        temp = temp->next;
    }
}
Clara
  • 9
  • 1
    Does this answer your question? [Changing address contained by pointer using function](https://stackoverflow.com/questions/13431108/changing-address-contained-by-pointer-using-function) – kaylum Jun 05 '21 at 03:57
  • 3
    `insert` is wrong because in C all function parameters are passed by value. It means `root` is a local variable in that function and setting it does not change the caller's (`A`) value. Read the duplicate post for more details and fixes. – kaylum Jun 05 '21 at 03:58

1 Answers1

3

It is necessary to pass as a parameter to "insert" function a pointer to the "struct LinkedList" pointer... not the "struct LinkedList" pointer itself.

Additionally, you are only calling "insert()" once in this version so you don't see and your "insert()" is not creating the linked list. Instead it is overwriting the "head" (your "A" pointer) every time it is called.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct LinkedList{
    int data;
    struct LinkedList* next;
};
/* prototypes */
void insert(struct LinkedList **root, int item);
void printList(struct LinkedList *head);

int main(){
    struct LinkedList *A = NULL;
    insert(&A, 3);
    insert(&A, 4);
    printList(A);
    return 0;
}
void insert(struct LinkedList **root, int item){

   struct LinkedList *newptr;

   newptr=malloc(sizeof(struct LinkedList));
   newptr->data= item;
   // ORIGINAL: root->next = NULL;
   newptr->next = *root;

   *root = newptr;
}
void printList(struct LinkedList *head){
    struct LinkedList *temp=head;
    while (temp != NULL){
        printf("%d\n", temp->data);
        temp = temp->next;
    }
}
TonyB
  • 927
  • 6
  • 13