I have a main
function that has a char, I am attempting to pass a pointer to that char
into a function and have it change it from A
to B
but it just doesn't seem to change it. The example shown here is just the current state of the code I have tried many different variations on it thus there may be other mistakes in there from simply clutching at straws.
int main() { char result = 'A'; setChar(&result); printf("%C", result); } void setChar(char* charToChange) { charToChange = "B"; }
As we know that a pointer contains the address of another variable and by dereferencing the pointer (using asterisk (*) operator), we can access the value to that variable and we can also update that value.
Pointers are passed as values, if you want to change a pointer, you have to pass a pointer to a pointer. A pointer as function parameter is basically a local variable, the changes only affect the pointer in this scope.
When you use pass-by-pointer, a copy of the pointer is passed to the function. If you modify the pointer inside the called function, you only modify the copy of the pointer, but the original pointer remains unmodified and still points to the original variable.
To update the value of a variable via pointer we have to first get the address of the variable and then set the new value in that memory address. We get the address via address of & operator and then we set the value using the value at the address of * operator.
What you want is *charToChange = 'b';
. The pointer charToChange
is a local variable (parameter) in setChar
, but you can change what it points to using the prefix *
operator and an assignment. Note that *charToChange
is a character, too, not a string.
You have to dereference the pointer passed to setChar()
in order to modify the value it points to, not the pointer argument itself.
You also have to use the character literal 'B'
instead of the string literal "B"
(which is a pointer to char
, not a char
).
void setChar(char* charToChange) { *charToChange = 'B'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With