Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a function change the value a pointer represents in C

Tags:

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"; } 
like image 776
Nick Avatar asked Jan 30 '11 19:01

Nick


People also ask

Can you change the value of a pointer in C?

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.

Can you change a pointer in a function?

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.

What happens when pointer is passed to a function?

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.

How do you change the value of a variable using pointers?

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.


2 Answers

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.

like image 152
Jeremiah Willcock Avatar answered Sep 20 '22 20:09

Jeremiah Willcock


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'; } 
like image 21
Frédéric Hamidi Avatar answered Sep 22 '22 20:09

Frédéric Hamidi