C struct pointer

4

What happens is the following, inside the ins_ult() function I can change the value of root->data , but outside the function the value remains NULL . Am I passing the parameter wrongly or using 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);
        }
}
    
asked by anonymous 21.08.2014 / 02:28

1 answer

3

You do not change root in the function. You need it to get a pointer to a Node pointer so that the value is not lost after the function returns.

This 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.

    
21.08.2014 / 03:16