Implementation of string arrays using pointers
C program to take input and print a string array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
int i, n;
char str[MAX][MAX];
printf("Enter the number of strings to be entered\t:");
scanf("%d",&n);
printf("\nEnter the strings\n");
for(i=0;i<n;i++)
scanf("%s",str+i);
printf("\n\nStrings entered are\n");
for(i=0;i<n;i++)
printf("%s\n",*(str+i));
getch();
}
Output
Enter the number of strings to be entered :5
Enter the strings
welcome
to
coursecrux.com
happy
coding!!!
Strings entered are
welcome
to
coursecrux.com
happy
coding!!!
Explanation
A 2-D array is actually a 1-D array in which each element is itself a 1-D array.
str points to 0th 1-D array.
(str + 1) points to 1st 1-D array.
(str + 2) points to 2nd 1-D array.
In general,
(str + i) points to ith 1-D array.
In above program, 2-D array is an array of string and 1-D array is a string which is basically an array of characters.
so, (str+i) points to the ith string and *(str+i) gives the ith string value.
str points to 0th 1-D array.
(str + 1) points to 1st 1-D array.
(str + 2) points to 2nd 1-D array.
In general,
(str + i) points to ith 1-D array.
In above program, 2-D array is an array of string and 1-D array is a string which is basically an array of characters.
so, (str+i) points to the ith string and *(str+i) gives the ith string value.