Ravi
Ravi

Reputation: 622

No output of array of strings

I want to create an array of strings Below is the program

char *s[6];
int n=6,i=0;
char str[10];
while(n--)
{
    scanf("%s",str);
        s[i]=str;
        i++;
}
for(i=0;i<6;i++)
    printf("%s\n",s[i]);

Six strings are accepted from the keyboard, but nothing is displayed on the output. Can anyone help me out here? Thanks!

Upvotes: 3

Views: 88

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

s[i]=str;

You are assigning same str to all s. All strings would be same on printing. If last string is empty for some reason, all would be empty.

Moreover you should reset n to 5 before second loop.

Fixes

while(n--)
{
    scanf("%s",str);
    if(i >= 6) break;  /* 1. Can not go beyond 6 */
    s[i]=malloc(strlen(str) + 1);  /* 2. Allocate */
    if(s[i]) strcpy(s[i], str); /* 3. Copy */
    i++;

}
n = 5; /* 4. reset */
for(i=0;i<n;i++)
    printf("%s\n",s[i]);
...

for(i = 0; i < n; i++) free(s[i]); /* 5. free */

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

The address of str is fixed. Thus in statement

s[i]=str;

each element of the array of character pointers s gets the same address. You coudl change the code snippet at least the following way

#include <string.h>
//...
#define N 6

//...

char s[N][10];
int n = N, i = 0;
char str[10];

while ( n-- )
{
    scanf("%9s", str );
    strcpy( s[i], str );
    i++;
}
for( i = 0; i < N; i++ )
    puts( s[i] );

The while loop would be better to write as a for loop

for ( i = 0; i < n; i++ )
{
    scanf("%9s", str );
    strcpy( s[i], str );
}

Also pay attention to that if your compiler supports Variable Length Arrays and the array s is a local variable of a function (for example of main) you could define it the following way

int n;

printf( "Enter the number of strings you are going to enter: " );
scanf( "%d", &n );

if ( n <= 0 ) n = N;
char s[n][10];

Upvotes: 3

Related Questions