I want to test pass pointer by reference in C, below is my test code.
I expect the result to be: "World!"
, but after I executed, I found that the result is indeterminate.
void parse(char **p)
{
char str[] = "Hello World!";
char *token = strtok(str, " "); // token points to 'H'
*p = strtok(NULL, " "); // *p (buf) points to 'W'
}
int main()
{
char *buf = (char*)malloc(20 * sizeof(char));
buf = "How are you?";
parse(&buf);
printf("%s\n", buf);
}
My View:
(1) In main()
: buf
points to 'H'
("How are you?"
's first char 'H'
) (Suppose address of 'H'
is 0x10
)
(2) parse(&buf)
makes pointer p
points to buf
(i.e. *p = buf = 0x10
)
(3) After 2 times of strtok()
, *p
(buf
) points to 'W'
(Suppose address of 'W'
is 0x20
)
(4) Now, return to main()
, buf
points to 0x20
(5) I expect printf("%s\n", buf);
should print "World!"
, but instead print something like "garbled text".
I have tried debugging, but I don't think I have mistaken anything above.
Can someone quell my doubts?
Thanks in advance.