In the last tutorial I told you about the subtle difference between gets() and scanf() function. Apart from this I also told you about the two ways to print strings on the screen. Armed with the basic concepts of strings lets move our journey forward to learn some advance topics of strings. Today I will tell you about the usage of strings with pointers and I will tell two-dimensional array of characters.
String in C
Strings and Pointers
Strings can be stored in two ways. The first one is quite obvious that we have used till now. In the second method we can store strings in character pointer. Given below is one small example.
char name[]="TheCrazyProgrammer"; char *p="TheCrazyProgrammer";
First one is quite familiar to you. But the second one is bit different. In the second one we are storing the address of first character of the string in character pointer. When compiler encounters this, it immediately store the entire string at some place and store the base address of it in character pointer.
Now one million dollar question which will hit your mind. Which one is better and why?
Well the answer depends on the condition or situation in which we have to use strings. But still programmers generally prefer the second method because it gives some flexibility to them.
Given below are two examples of such conditions.
void main( ) { char name[]="Hello"; char name1[20]; char *a ="Good Morning"; char *b; name1=name; //error b=a; //works }
Explanation
As you can see we cannot directly copy one string to another. It will result in an error. Why? This is because by accessing the name of the string we will only get the base address of the string. So when we directly copy one string to another. It will only try to copy the base address of one string to another string that will result in an error.
On the other hand by using character pointer we are only storing base address of string which can be easily copied to another character pointer.
void main( ) { char name[]="Hello"; char *name2="Hello"; name="Bye"; //error name2="Bye"; //works }
Explanation
When we store string in the normal way then we cannot initialize it multiple times. On the other hand we can again initialize the array when we store it in character pointer.
2D Array of Characters
In the earlier tutorials I already told you about the 2D arrays. 2D arrays of characters are also similar to them. So consider the below program to understand its working.
#include<stdio.h> void main() { char name[4][10]={ "Neil", "James", "John", "Ricky" }; int x; for(x=0;x<4;x++) { printf("%sn",name[x]); } }
Output
The program is self explainable. I have only used character 2D arrays and I have initialized it with some names. To print those names of the screen I have used one for loop. In the printf() function I have just incremented the subscript row wise to access all the names.