4thSpace
4thSpace

Reputation: 44332

How to manipulate variable in function?

In the example below, I pass a char into a function as a pointer. When the function prints out the memory address of the char, it is a different address. Am I dealing with two different variables in this case? Isn't that the same result as if I didn't use a pointer in the function argument (same as pass by value)?

char a = 'a';
printf("a=%p\n", &a);
showString(a);

//function 
void showString(char *c){
  c='b';
  printf("c=%p\n", &c);
}

c is assigned the value 'b'. But if I check a after the function call, it still has the value 'a'. How does the above need to change so the value assigned in the function carries over outside of the function?

Upvotes: 1

Views: 502

Answers (2)

Your function should look like

//function 
void showString(char *c) {
    *c = 'b';
    printf("c=%p\n", &c); //<---to print the address of C
    printf("c=%c\n", *c);  //<---to print the value that C is pointing
}

and when you call it you should pass the Address of a

char a = 'a';
printf("a=%p\n", &a);
showString(&a);   //<---&a and not a

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726649

You are not using the pointer correctly: rather than assigning a new value to the object the pointer points to, you assign the pointer itself.

The call should use the address-of operator, and the assignment should be with the dereference operator:

showString(&a);
printf("a=%p\n", (void*)&a);
...
void showString(char *c){
    *c='b';
    printf("c=%p\n", (void*)c);
}

Now both printouts will produce the same address, and the value of char a in the calling function should change.

Note 1: The reason the compiler allowed c = 'b' assignment is somewhat odd: 'b' is considered a character constant, char is considered an integral type, and C lets you assign integers to pointers with the assumption that you know what you are doing better than the compiler.

Note 2: When you print a pointer with %p, and the pointer type is neither void* nor char*, a cast to void* is required. You are printing char*, so it can go without a cast, but I added the cast anyway, in case you want to try this out with pointers of a different type.

Upvotes: 6

Related Questions