0

I have a node struct that has a function which will increment it's valuestruct

node {
  int value;
  struct node * left;
  struct node * right;
  void (*incrementValue)(struct node);
};

void incrementNodeValue(struct node this){
  this.value ++;
  printf("the value is now %d\n", this.value);
}

int main(){
  struct node firstLeft = { 5, NULL, NULL, incrementNodeValue };
  struct node firstRight = { 15, NULL, NULL, incrementNodeValue };
  struct node start = { 10, &firstLeft, &firstRight, incrementNodeValue };
  start.incrementValue(start);
  printf("%d\n", start.value);
  return 0;
}

My intention is that start.incrementValue will increase the value from 10 to 11.
When I compile and run this code (with no warnings), it prints

the value is now 11

10

So I know that the value is changed in the function, but once it exits the function seems no to have had any effect.

3
  • I tried doing exactly what you said, but it gave the error: error: ',' expected (got "&") Commented Jan 6, 2018 at 22:10
  • Yeah, I think I mixed my c++ and c syntax, sorry about that. Commented Jan 6, 2018 at 22:13
  • 1
    don't use this as a variable name. Everyone will think you're coding c++... Commented Jan 6, 2018 at 22:47

1 Answer 1

1

void incrementNodeValue(struct node this) declares a function that receives the value of a struct node. The value is only a copy of the contents. So the function only changes a copy; it does not change the original start object in the main routine.

To change the original object in the function, change the declaration so the function receives the address of a struct node:

void incrementNodeValue(struct node *this)

Then change the call so it passes the address:

start.incrementValue(&start);

Inside the function, you have to change the code to use this as a pointer rather than as a struct, so this.value becomes this->value.

And you will need to change the declaration inside the struct node to:

void (*incrementValue)(struct node *);
Sign up to request clarification or add additional context in comments.

1 Comment

this is correct. I am new to stack overflow so it won't let me accept your answer for another 6 minutes, but this did work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.