How do I change variables using external functions in C/C++?

Question:
How do I change variables using external functions in C/C++?
Repl link:

#include <stdin.h>

void changeVar(int* ptr, int newValue) {
  // somehow change the value of the variable that has the address of {ptr}
}

int main() {
  int num = 0;
  changeVar(&num, 32);
  printf("%d\n", num); // should print `32`
}

You’re on the right track, you just need to access the pointer and change the value stored at that location:

*ptr = newValue;

Using the * operator before a variable storing a pointer allows you to directly access the pointer’s value.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.