Pointers - 8 Pointer & Strings

Pointer & Strings


Like pointers and arrays, strings can also be operated using  pointers. As we know strings are array of characters ends with a special character called null character. Now we will see an example on handling strings using pointers.

/* Program to convert given string to uppercase */

# include< stdio.h >
# include< ctype.h >
main()
{
char word [ 30 ];
char *p;

printf ( "\n Enter any word " ) ;
scanf ( "%s", word );

p = word; /* Address of  first character of string is assigned to pointer variable p */

while ( *p != '\0' )
{
printf ( "%c", toupper( *p ) );
p++;
}

}


In the above program initially a character array 'word' is declared along with a pointer to character 'p' is also declared. A string will be accepted from user. Then Address of  first character of string is assigned to pointer variable p. In while each character will be accessed using pointer and it is printed in uppercase using a special function toupper() and repeated until it reaches null character. A header file ctype.h contains number of functions related to character operations like, toupper(), tolower(), isupper(), islower(), isdigit(), ispunct(), isspace() etc.

Comments