I have a question that is raised from this discussion: C - modify the address of a pointer passed to a function
Let's say I have the following code:
#include <stdio.h>
foo(char **ptr){
*ptr++;
}
int main()
{
char *ptr = malloc(64);
char arr[] = "Hello World!";
memcpy(ptr, arr, sizeof(arr));
foo(&ptr);
foo(&ptr);
printf("%s",ptr);
return 0;
}
I was wondering what the output of this program would be and I thought that it should be llo World!
.
After some investigation I found the question linked above and realized that, in C, parameters to functions are always passed by value. So far there was no problem. When it comes to change *ptr++;
expression to -> *ptr = *ptr +1;
output becomes: llo World!
.
At this point, I can say that I am a little confused. In order to change pointer address, we need a double pointer. That is fine, but why do post increment operations differ? Is it because of the operator precedence?
Here I tried the example in an online C compiler.