Pointer and String

Pointer and String

Published by: Nuru

Published date: 21 Jun 2021

Pointer and String Photo

Pointer and String

A string in C is merely an array of characters. The length of a string is determined by a terminating null character: '\0'. We can take a char pointer and initialize it with a string constant.

For example:
char *ptr= "Programming”;
Here ptr is a char pointer that points to the first character of the string constant “Programming” i.e. ptr contains the base address of this string constant.

Now let‟s compare the strings defined as arrays and strings defined as pointers.
char str[ ]="Chitwan”;
char *ptr="Nawalparasi”;

These two forms may look similar but there are some differences in them. The initialization itself has a different meaning in both forms. In array form, initialization is a short form for

char str[ ]={„C‟,‟h‟,‟i‟,‟t‟,‟w‟,‟a‟,‟n‟,‟\0‟}
while in pointer form, the address of string constant is assigned to the pointer variable.

Now let us see how they are represented in memory.

Pointers and string

Here string assignments are valid for pointers while they are invalid for strings defined as arrays.
str = “Narayangarh” //invalid
ptr = ”Butwal” //valid

Array of pointers with string

Array of pointers to strings is an array of char pointers in which each pointer points to the first character of a string i.e. each element of this array contains the base address of a string.
char *arrp[ ]={“white”,”red”,”green”,”yellow”,”blue”};

Here arrp is an array of pointers to a string. We have not specified the size of the array, so the size is determined by the number of initializers. The initializers are string constant. arrp[0] contains the base address of string “white” similarly arrp[1] contains the base address of string “red”

Pointers and string