hexidian
hexidian

Reputation: 81

C function pointer in a struct not changing the values when called

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.

Upvotes: 0

Views: 642

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224310

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 *);

Upvotes: 1

Related Questions