The first line of your code reads:
char* name = "Any name";
- Here you declare
name, which indeed is a character pointer.
- And you create a string,
"Any name" which is an array of characters ending with a null byte. This string will be stored in memory, somewhere on the heap.
- And finally you assign the address of that string to the variable name.
That is why
name points to the address of the string
The fourth line of your code reads
name = "Any other name";
- Here you create a string
"Any other name". This string will also be stored in memory, somewhere else on the heap.
- and you assign the address of the new string to name.
So you assigned a new value (address) to the variable
The end result will look like this:
You can see a live version of this visualization at C Tutor; After waiting a couple of seconds, you can step through your code by clicking on the
Forward > button. (I added one variable to make the visualization more clear)
Your question was:
I thought that the addresses would be the same since name is a pointer to an address, so, why does the address of this pointer change after I change what was stored in that address from "Any name" to "Any other name"?
Well, you didn't change what was stored in that address. The first string still reads
"Any name". But your pointer does not point to it anymore.
And the address of the pointer did not change. Remember that
name is a pointer to characters. The address of the pointer is the address of
name, which has not changed at all. This address still points to the same piece of memory, in which an address could be stored. After the first line, it contained
0x427574, which is the address of
"Any name". And after the fourth line, it contained
0x42757d, which is the address of
"Any other name".
So you didn't change the address of
name, you changed the contents of
And you didn't change the first array-of-characters, you created a second array-of-characters.
And to quote Cliff B:
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)