Char Pointers in C

The Code:

I decided to write a quick bit of code to reinforce my understanding of char pointers in C; especially Char** as I recently confused myself. Firstly lets get straight to the code as it is the best way to learn. The code comments should explain what each line is doing however additional explanation of the steps is provided further down the page.


I have quickly put together a diagram to help visualise how the pointers are interacting with each other in memory.

Diagram showing how the pointers interact in memory


Firstly I have declared a string literal called “Bob” which C stores within an area of memory called “Constant”. Line 18 declares the constant string literal and then declares a pointer called “name” which points to the memory address of “Bob”. The diagram shows the value of name containing the memory address of “Bob”. Printing “name” will print the value of the pointer while “&name” prints the address of the pointer itself.

Line 11 declares a pointer pointer “Char**” and stores the address of the name pointer in its value as shown above. The string literal can be accessed with a single * (Deference), printing with “p_name” will give you the value of “p_name” which is the address of the “name” pointer itself, dereferencing with ‘*’ gets the value of “name” which is “Bob”. Next I show how changing the value of “name” to a new string literal called “John” changes the value returned when dereferencing “p_name”.

I have shown how a void pointer is declared and cast to a pointer pointer for use elsewhere. This is then used in two different ways; firstly I dereference the void pointer back to the string literal “John”. This is fixed and any update to “name” has no effect on “test”. Finally I pass “test2” the address of the name pointer and therefore any updates to “name” reflect when dereferencing “test2” as shown when updating “name” to point to “Charles”.

Code Output:

The result of the code running will look like this except the memory addresses will be different. The operating system will decide where to store the variables and constants.

Output of the code run showing pointers, values and memory addresses
Output of the code run


None although Head First C provides a good explanation of various C topics such as pointers.