In the previous chapter, we have seen how pointer and arrays are related. Strings and pointers are also very closely related. Since a string is an array, the name of the string is a constant pointer to the string . This pointer stores the base address of the string and can be used to perform operation on the string.
Example: Display characters of string using array
char str[20]=”Sample Message”;
for(i=0; str[i]!=‘\0’;i++)
printf(“%c”, str[i]);
Example: Display characters of string using pointer
char str[20]=”Sample Message”;
char *ptr=str;
for(i=0; *ptr!=‘\0’;i++)
printf(“%c”,*(ptr+i)); //or ptr++
Importance of NULL character
As seen above, every string has a special NULL character at the end. The importance of the character is to indicate the end of a string. Consider the for loop given below:
for(i=0; *ptr!=‘\0’;i++)
printf(“%c”,*(ptr+i));
If we have to access the string character by character, we need to know when the string ends. If the string does not have the terminating character, it would not be possible to identify the end of the strings. Hence, this character is very important.
Comments
Post a Comment
Please give us feedback through comments