char arrays and null terminated strings

Character arrays are designated by

Hence, we make an array of characters called “myName” with 10 elements:

char_array_memory

Any left over elements that are not taken up by the initialization will have ” or NULL filled in.

Using pointer to display string

myName is actually a const pointer to the first element of the array. When we use cout to display char arrays, it displays all the data from the pointer up until the terminating NULL. Since our pointer is currently at the beginning of the array (R), cout will display the full name Ricky.

Adding a byte (1) to the pointer will display one character further down the array. Note that a char is equal a byte.
Adding n bytes will display characters further down the array.

Result:
my name is: Ricky
my name is: icky
my name is: cky
my name is: ky
my name is: y

Using address of element to display string

myName[0] gets you the first element ‘R’.

If you use &myName[0], it gets you the ADDRESS of the first element. Hence, the compiler will display all data from that address up to a NULL. Hence &myName[0] will display ‘Ricky’ also.

Result:
&myName[0] displays: Ricky, myName[0] is: R
&myName[1] displays: icky, myName[1] is: i
&myName[2] displays: cky, myName[2] is: c
&myName[3] displays: ky, myName[3] is: k
&myName[4] displays: y, myName[4] is: y

What if the element is NULL?

A better way to display an element is to check for NULL

In our case index 5 and on would give us a NULL.

Getting the address

Use void pointer to get the memory location.
std::cout << (void*)&myName[0] << std::endl; std::cout << (void*)&myName[1] << std::endl; std::cout << (void*)&myName[2] << std::endl; std::cout << (void*)&myName[3] << std::endl; std::cout << (void*)&myName[4] << std::endl; std::cout << (void*)&myName[5] << std::endl; Result: 0x7fff5fbff86e 0x7fff5fbff86f 0x7fff5fbff870 0x7fff5fbff871 0x7fff5fbff872 0x7fff5fbff873 Remember that hex is 0 - 9, a - f and each increment is a byte. Hence R is at address 0x7fff5fbff86e
i is at address 0x7fff5fbff86f
c is at address 0x7fff5fbff860
k is at address 0x7fff5fbff861

where each char is a byte. Also notice that the string terminating NULL also has a address at 0x7fff5fbff873.