Pointer of struct in C

Asked

Viewed 329 times

4

What happens is this, within the function ins_ult() I can change the value of root->data, but outside the function the value remains NULL. I’m passing the parameter the wrong way or using the malloc incorrectly?

#include<stdlib.h>
#include<stdio.h>
typedef struct Node_t{
        void *data;
        struct Node_t *next;
}Node;
int main(){
        Node *root;
        root=NULL;
        ins_ult(root,100);
        printf("%d,%d\n",root->data);
}
void ins_ult(Node *root, void *data){
        if(root == NULL){
                root = malloc(sizeof(Node));
                root->data = data;
                root->next = 0;
                printf("%d\n",root->data);
        }
}

1 answer

3


You do not change root at the function. You need it to receive a pointer to a pointer of type Node so that the value is not lost after the function returns.

That code:

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

struct node{
  void *data;
  struct node *next;
};

void ins_ult(struct node **root, void *data){
  if(*root == NULL){
    *root = (struct node *)malloc(sizeof(struct node *));
    (*root)->data = data;
    (*root)->next = 0;
    printf("%d\n", (*root)->data);
  }
}

int main(){
  struct node *root;
  root=NULL;
  ins_ult(&root, 100);
  printf("%d\n", root->data);
  return 0;
}

will print 100 twice on the screen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.