For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
The declared variable in this declaration
char ch;
is not used in the program and should be removed.
And neither declaration from the header <string.h>
is used in your program. So the header could be removed.
You declared a variable length array of pointers to the type char
char *a[n];
However the elements of the array were not initialized and have indeterminate values. As result the program has undefined behavior due to this statement in the for loop
gets(a+i);
You have to allocate memory for each string you are going to enter.
Also take into account that the function gets
is unsafe and is not supported any more by the C Standard. Instead use the function fgets
. Moreover the argument in the function call must be *( a + i )
instead of a + i
because the type of the last expression is char **
instead of the required type char *
.
So a valid code can look for example the following way
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
size_t n;
const size_t SIZE = 20;
printf( "no of elements: " );
if ( scanf( "%zu%*c", &n ) != 1 || n == 0 ) n = 1;
char * a[n];
for ( size_t i = 0; i < n; i++ )
{
*( a + i ) = malloc( SIZE );
}
puts("string");
for ( size_t i = 0; i < n; ++i )
{
fgets( *( a + i ), SIZE, stdin );
}
puts("-----");
for ( size_t i = 0; i < n; ++i )
{
printf( "%s", *( a + i ) );
}
puts( "-----" );
printf( "%s", *a );
puts( "-----" );
printf( "%s", *( a + 2 ) );
for ( size_t i = 0; i < n; i++ )
{
free( *( a + i ) );
}
return 0;
}
Its output might look like
no of elements: 5
string
A
B
C
D
E
-----
A
B
C
D
E
-----
A
-----
C
Pay attention to this statement
if ( scanf( "%zu%*c", &n ) != 1 || n == 0 ) n = 1;
After reading the variable n
using format specifier &zu
you need to remove from the input buffer the new line character that corresponds to the pressed key Enter. Otherwise the next call of fgets
will read an empty string.