String and Pointer
The string itself act as a pointer.
The string name is a pointer to the first character in the string.
string name == &string[0]
As we all know, the string is a character array which is terminated by the null '\0' character.
Example
char str[6]="Hello";
Where,
str is the string name and it is a pointer to the first character in the string. i.e. &str[0].
Similarly, str+1 holds the address of the second character of the string. i.e. &str[1]
To store "Hello", we need to allocate 6 bytes of memory.
5 byte for "Hello"
1 byte for null '\0' character.
Let's print each character address of the string 'str'
Example
#include<stdio.h> int main() { char str[6] = "Hello"; int i; //printing each char address for(i = 0; str[i]; i++) printf("&str[%d] = %p\n",i,str+i); return 0; }
%p format specifier is used to printing the pointer address.
str[i] == *(str+i)
str[i] will give the character stored at the string index i.
str[i] is a shortend version of *(str+i).
*(str+i) - value stored at the memory address str+i. (base address + index)
Let's print each character of a string using *(str+i)
Example
#include<stdio.h> int main() { char str[6] = "Hello"; int i; //printing each char value for(i = 0; str[i]; i++) printf("str[%d] = %c\n",i,*(str+i)); //str[i] == *(str+i) return 0; }