Wednesday, November 2, 2011

Pointers and Strings in C programming language

Suppose we wish to store “Hello”. We may either store it in a string or we may ask the C compiler to store it at some location in memory and assign the address of the string in a char pointer. This is shown below:

char  str[ ] = "Hello" ;
char  *p = "Hello" ;

There is a subtle difference in usage of these two forms. For example, we cannot assign a string to another, whereas, we can assign a char pointer to another char pointer. This is shown in the following program.

main( )
{
      char  str1[ ] = "Hello" ;
      char  str2[10] ;

      char  *s = "Good Morning" ;
      char  *q ;
      str2 = str1 ; /* error */
      q = s ; /* works */
}

Also, once a string has been defined it cannot be initialized to another set of characters. Unlike strings, such an operation is perfectly valid with char pointers.

main( )
{
      char  str1[ ] = "Hello" ;
      char  *p = "Hello" ;
      str1 = "Bye" ; /* error */
      p = "Bye" ; /* works */
}

No comments:

Post a Comment