Changing struct/variable content in C

cmallocparameter-passing

I would like to get some help with the following question.
I have a struct Node and I want to change it's insides using some method.
and I want to print the content of the changed struct inside my main method.
how do I get the struct changed and see the changed value in my main without returning the node as a return value.
I guess it might be solved with passing the struct Node as a pointer and then editing it.
what is the right way to do so?

for example:

typedef struct Node{
   struct Node * right;
   struct Node * left;
   void * data;
}Node;

void insert(void * element, Node* root){
   if(root==NULL){
       root=(Node*)malloc(sizeof(Node));
       root->data=element;
   }
}


int main(){
    Node a;
    int b=8;
    insert(&b,&a);
    printf("%d",*(int*)a.data);
    return 0;   
}

printf doesn't print 8 it prints 1 (i guess some garbage)

Best Answer

It sounds like you are trying to do the following

  • Create a struct in one method, say main
  • Pass it to a second method, say example
  • Have example modify the struct and have the results visible in main

If so then the way to do this in C is by passing the struct as a pointer to example.

struct Node {
  int data;
  struct Node* pNext;
};

void example(struct Node* pNode) {
  pNode->data = 42;
  pNode->pNext = NULL;
}

int main() {
  struct Node n;
  example(&n);
  printf("%d\n", n.data);
}

EDIT

Responding to the updated question.

To see the result of a modification of a Node you must pass a Node*. And accordingly to see the result of a Node* modification you need to pass a Node**. Essentially you need to pass one more level of indirection than the value you want to mutate / return.

void insert(void* element, Node** ppRoot){
  if (NULL == *ppRoot) {
    Node* pTemp = malloc(sizeof(Node));
    pTemp->data = element;
    *ppRoot = pTemp;
  }
}
Related Topic