0

here i trying to send the address of my node root which begins with a null value but i send it to the create function to allocate memory for it.it seems to allocate memory for just the node inside create and not for root.how can i allocate memory for root?not using root=create() where the function just returns address of the created node .i want to just pass a variable and allocate memory to it in different function.

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
};
struct node *root=NULL;
void create(struct node *node)
{
    int num;
    printf("enter the data");
    scanf("%d",&num);
    node=(struct node*)malloc(sizeof(struct node));

    node->data=num;
        printf("%d",node->data);

}
int main()
{
    create(root);
    if(root==NULL)
        printf("null");
    printf("%d",root->data);
    return 0;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Mr Josh
  • 120
  • 2
  • 11
  • 1
    *Return* the pointer instead. Otherwise you need to research *emulating pass by reference in C*. – Some programmer dude Feb 16 '19 at 10:42
  • Some other remarks (I was writing an answer when the question was marked duplicate) : check _scanf_ success, check _malloc_ result before to dereference it, an _else_ is very missing in `if(root==NULL) printf("null"); printf("%d",root->data);` !, add a terminating `\n` when you print the data to flush the print, when you print a message before an input you can use _stderr_ to have it flush without `\n` – bruno Feb 16 '19 at 11:02
  • thanks guys it was really helpful.using a double pointer for it – Mr Josh Feb 17 '19 at 04:14

0 Answers0