[Solved] How a pointer to a string works in a function?


Snippet 1

char a[200],*p;

Defined a block of 200 characters ,a, and a pointer, p, to a block of one or more characters.

gets(a); // cin.get(a,200);

Read some user input into memory block a

p=a;

Points p at block a. p can now be used as a reference to the same thing as a

strcpy(p,p+1);

Copy part of the memory block over itself. NOTE: this invokes undefined behaviour because the to and from buffers in strcpy overlap (See http://en.cppreference.com/w/cpp/string/byte/strcpy). The results may be unusual, ranging from “Looks like it works!” to more fantastic, such as the computer making it rain unicorns.

So, say a is created at memory location 10. Data is read into the block starting at location 10. Then p is set to point at location ten. Then the memory starting at location 11 is copied over the memory starting at location 10. Since a is at 10, printing a prints the altered data. Since p is still pointing at 10, printing p will print the same thing as a.

Snippet 2:

char a[200],*p;

Defined a block of 200 characters ,a, and a pointer, p, to a block of one or more characters.

gets(a); // cin.get(a,200);

Read some user input into memory block a

p=a;

Points p at block a. p can now be used as a reference to the same thing as a

p++;

Moved where p pointed over one slot to the right. Copied nothing. Just changed the address that p points at.

So, say a is created at memory location 10. Data is read into the block starting at location 10. Then p is set to point at location 10. Then p is set to point at memory location 11. The values in memory block a are unchanged. Since a is still at 10, printing a prints the unchanged data. Since p is now pointing at 11, printing p will print the from the second character of a onward.

10

solved How a pointer to a string works in a function?