Pointers and Character Strings

As we know that in C language strings are represented by one-dimensional array of characters terminated by a null character '\0', where null character indicates the end of the string. The character strings are declared and initialized as follows :
 char str[] = "Hello";
The above statement declare and initialize a string array str, and the compiler automatically inserts the null character '\0' at the end of the string. The above string declaration can be represented in memory as follows:


Each character in a character array takes one byte of space. The array str holds the address of first element of array which is 'H', and its address is 2000. It means, we can also create a character pointer which store the address of string str in it. For example, lets look at the statement below :
 char *ptr = str;
The character pointer points to the string array str. It can be represented in memory as follows :


The pointer ptr points to the first element of character array. Now lets see a C example program.
#include <stdio.h>

int main() {
  char str[] = "Hello";
  printf("%s\n", str);
  char *ptr = str;
  printf("%s\n", ptr);
  return 0;
}
Output :

Hello
Hello

C supports an alternative method to create strings using pointer variables of type char. For example :
 char *str = "Hello World";
The above statement create a string for the literal and then stores its address in the pointer variable str. The pointer variable str points to the first character of the string "Hello". We can also use the run-time assignment for a giving values to a string pointer for example :
 char *str;
 str = "Hello world"
Now lets see some C example :

Example 1 :
#include <stdio.h>

int main() {
  char *str = "Hello world";
  printf("%s\n", str);
  return 0;
}
Output :

Hello world

Example 2 :
#include <stdio.h>

int main() {
  char *str;
  str = "Hello world";
  printf("%s\n", str);
  return 0;
}
Output :

Hello world

Next Topic :