Pointers and Strings

From WikiEducator
Jump to: navigation, search

Pointers and Strings:

We already know that a string is not just a 1-dimensional array of characters but it is 1 – dimensional array of characters which is terminated by a Null (‘\0’) character. This can be well defined in terms of following diagram :

 char MyName [30] = "Kamal";

Also we have gathered knowledge that the name of a 1-dimensional array is itself a pointer to the first member of that array. So the above diagram can be more clearly represented as:


Q. Now keeping the above figure in mind fill in the following blanks :

 a) MyName + 2  =  ____________
 b) *(MyName +1)    =      ____________
 c) *(MyName + strlen(MyName) ) =     _____________

Check this out with your local teacher.

Conclusions :

 i) We know that a string is terminated by a null character. 
ii) A string name is a pointer to the first character i,e name of the string is

holding the base address of the string.

By analyzing i) and ii) above we find that now there is no need to declare a string like char str[30]; (as we have done in class XI). This can be more dynamically declared as char *str (The benefit here is that we don’t have to fix the size). Only declaring a character pointer is sufficient to hold an entire string, since the end point of the string will be automatically marked by NULL (‘\0’) character, during run time. Hence:

     char str[30]  is same as writing    char * str = new char[30];

or more dynamically as ,

     char *str;

Whatever string you assign to this it will accommodate, since the only need is to mark the beginning and end memory locations of the string.