Brother, you have decleared char array as char n[50];
which can store only maximum of 50 charecters as a string at 'n'. As you want to store 'a' strings; you would have to allocate memory for 'a' strings as char[a][50];
and then store the strings at respective memory locations using for loop.
Hence, the program would be as:
#include<stdio.h>
#include<string.h>
int main()
{
int a;
scanf("%d",&a);
char n[a][50];
for(int i=0;i<a;i++)
{
scanf("%s",n[i]);
}
for(int i=0;i<a;i++)
{
printf("%s\n",n[i]);
}
return 0;
}
As each string can vary in size, this type of declearation may lead to loss of memory or loss of data. Hence, more efficient way to solve the problem would be to allocate memory for a input string and store it there. Once stored, we can use the string by just it's base address, hence we would just store the base addresses of every stored string in a array of pointers to char(string). Hence, char *n[a] ;
would help us to store pointers to char. Hence the solution would be as :
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
int main( )
{
int len, i, a ;
char n[ 50 ] *p ;
scanf("%d", &a);
char *names[a] ;
for ( i = 0 ; i < a ; i++ )
{
printf ( "Enter string1 : " ) ;
scanf ( "%s", n ) ;
len = strlen ( n ) ;
p = ( char * ) malloc ( len + 1 ) ; /* +1 for accommodating \0 */
strcpy ( p, n ) ;
names[ i ] = p ;
}
for ( i = 0 ; i < a ; i++ )
printf ( "%s\n", names[ i ] ) ;
return 0 ;
}
In this program, we have first received a name using scanf( ) in a string n[ ]. Then we have found out its length using strlen( ) and allocated space for making a copy of this name. This memory allocation has been done using a standard library function called malloc( ). You may read more about malloc here. Then, we just copied the string to the memory location by using strcpy( ) library function in string.h and stored the address in the array.
We have used the same array to print the stored strings by their memory locations, in another for loop.
You may read all about this in the book Let Us C - by Yashwant Kanetkar
in Chapter : Strings
and Chapter : Handling Multiple Strings
.
Note : Some compilers don't allow to declear variable after using library functions as we have used char[a][n]
and char *names[a] ;
after scanf(). To solve this, you would have to predefine the maximum number of strings to take as input or else you would have to modify the program and use dynamic memory allocation more efficiently. I am not posting it here as this would become a little more complex.