Friday, 30 March 2012

Pointers and character string


Pointers and character string

Strings in C language are treated as character array. String is declared as follows:

char name[10];
if initialized its value then
          char name[4]=”Shiv”;
Here, compiler automatically insrts the null ‘\0’ character at the end of the string.

In C string can be created using pointer variable of type char
Ex,
char *name=”Shiv”;

S
H
i
v
\0
0
1
2
3
4


 


                     
            name
Here a pointer variable name points to the letter S in the string “Shiv” somewhere in memory.
The string can be printed either using prinf() or puts() function as follows:
                   printf(“%s”,name);
                   puts(name);


Array of pointer

As the array of integers , float same as it is also possible to create array of pointers. Pointer contains an address and array of pointer would be a collection of addresses.

A multi dimensional array can be expressed in terms of an array of pointers rather than as a pointer to a group of contiguous arrays.

For ex,
int  *x[10];
here, x is the array of pointer of integer type

 The most common use of array of pointers is with strings. The start of the string is indicated address by a pointer to the first character and the end of the string is marked by null character. By declaring and initializing an array of pointers to tyoe char , possible to access and manipulate a large number of strings using the pointer array. Each element in the array points to a different string.It can be declared as follow :
          char *ptr_var[expression1];
Here ptr_var is the name of char pointer array and expression1 specifies the number of strings in array.

Ex,
char *name[3]={“Ram”,”Madhav”,”Shiv”};

Instead of making each row a fixed number of character , a pointer to a string made string of varying length.

R
a
m
\0



M
a
D
h
a
v
\0
S
h
I
v
\0



The character array with the rows of varying length are called “ragged arrays”.


Posted By : Ruchita Pandya

No comments:

Post a Comment