You know that there are arrays of primitive data types like integers, characters, float etc. Question may be arise in your mind, array of strings is possible or not ?
Answer is yes.
One way to do this is using two dimensional character array and other is using array of character pointers.
Answer is yes.
One way to do this is using two dimensional character array and other is using array of character pointers.
Method 1 - using two dimensional char array :
char arr[][10] = {"We", "like", "to", "learn"};
0x2000 | ‘W’ | ‘e’ | ‘\0’ | |||
0x200A | ‘l’ | ‘i’ | ‘k’ | ‘e’ | ‘\0’ | |
0x2014 | ‘t’ | ‘o’ | ‘\0’ | |||
0x201D | ‘l’ | ‘e’ | ‘a’ | ‘r’ | ‘n’ | ‘\0’ |
Memory representation of two dimensional array
All the shaded cells contain garbage values. First Column indicates memory locations of first byte of each string. As you see that in this case memory locations are contiguous.
Method 2 –using array of character pointers:
char *arr[] = {"We", "like", "to", "learn"};
Here, the difference between earlier is that since it is the array of character pointer of string literals, you can’t modify the strings, but you can replace it with new string literals or strings.
No comments:
Post a Comment