Reputation: 313
I use sprintf() to fill my string, but when I'm not done, I found something strange, the var which names test can be modified even it is a argument, I thought it was just like a Rvalue when calling function, or here is somewhere I didn't notice, and the following is my code and output.
Thanks.
#include <stdio.h>
#include <stdlib.h>
void Encap(char str[9])
{
printf("%s\n", str);
sprintf(str, "hi e");
printf("%s\n%p\n", str, &str);
}
int main()
{
char test[9] = "ABC";
printf("%s\n", test);
Encap(test);
printf("%s\n%p\n", test, &test);
system("pause");
return 0;
}
Output
ABC
ABC
hi e
0061FF10
hi e
0061FF27
Upvotes: 0
Views: 1209
Reputation: 389
You are passing pointer to function, It will surely change value at the memory location. As you are passing pointer, another copy of pointer will be created and which will be used in function.(Whenever we call to a function, copy of variable is made and operations are done on that copy variable). Here the variable is of type pointer, hence another pointer variable will be created which will be pointing to same memory locations as pointed by test but will be having different address. That's why two different memory address gets printed as you are printing address of two different pointers.
Upvotes: 2
Reputation: 48010
You declare an array test
, and you pass it to the function Encap
. Your question is a little unclear, but there are two things which may be surprising you:
Encap
, you are modifying the contents of the array.Encap
returns, back in the caller, the modifications to the test
array persist.(You also asked about "rvalue", which can be an important concept, but it doesn't apply here in the way that you expect.)
The reason this works the way it does is because of two different things:
test
to the function Encap
, you do not pass the entire value of the array. what actually gets passed is just a pointer to the array;s first element.Encap
, you are not modifying the pointer that was passed, instead, you are modifying the memory that the pointer points to. You are using the pointer as a value (a pointer value) to know where the memory is that you should modify -- and this ends up being the test
array up in main()
.Upvotes: 3