Wednesday, October 21, 2009

Array of character pointers

/* A simple demonstration of an array of character pointers.
notice the declaration: char* family[] : similar to how you would declare an integer array int arr[].

Here is a layout of the family array in memory:

----------------------------------
| x | y | p | q | r | '\0'|
----------------------------------
A A+8 A+16 A+24 A+32

The address of family[0] is A. A points to X which contains the string "Homer".
The address of family[1] is A+8. A+8 points to Y which contains the string "Marge".

Notice that the address of family[0], family[1],family[2] etc are spaced exactly 8 bytes apart. Strictly speaking, they are spaced
sizeof(char*) bytes apart in memory.

Each element of the family array points to an address in memory. So family[0] points to an address X in memory,
family[1] points to address Y etc. Here is a representation of "Homer" in memory:

----------------------------------
| H | o | m | e | r | '\0'|
----------------------------------
x x+1 x+2 x+3 x+4 x+5

x+5 points to the terminating NULL character .

Similarly family[1] contains Y which contains marge:

----------------------------------
| M | a | r | g | e | '\0'|
----------------------------------
y y+1 y+2 y+3 y+4 y+5

familyptr is declaread as char** . It is a pointer to a character pointer.

Initially familyptr is assigned to family. This means familyptr has the address A. *familyptr will then point to address X. When you
print the string from address X , it prints the value "Homer". Then familyptr is incremented familyptr++. Pointer arithmetic comes into
play here. since familyptr is a char** , familyptr++ increments the value by 8. So familyptr now becomes A+8. *familyptr will then point to address Y. When you print the string from address Y , it prints the value "Marge". You can thus increment and print all the members of the family.
*/
#include <stdio.h>
#include <string.h>
int main(){
char* family[]= {"Homer","Marge","Bart","Lisa","Maggie"};
char** familyptr;
familyptr = family;
//Homer
printf("%s\n",family[0]);
printf("%s\n",*familyptr);
//Marge
printf("%s\n",family[1]);
familyptr++;
printf("%s\n",*familyptr);
//Bart
printf("%s\n",family[2]);
familyptr++;
printf("%s\n",*familyptr);
//Lisa
printf("%s\n",family[3]);
familyptr++;
printf("%s\n",*familyptr);
//Maggie
printf("%s\n",family[4]);
familyptr++;
printf("%s\n",*familyptr);
return 0;
}

No comments:

Post a Comment