No string array output

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 lines are received from the keyboard, but nothing is displayed on the output. Can anyone help me here? Thank!

+3


source to share


2 answers


s[i]=str;

      

You assign the same to str

everyone s

. All lines will be the same when printed. If for some reason the last line is empty, all will be empty.

Also, before the second loop, you must reset n

to 5

.



difficult

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 */

      

+4


source


Fixed address str

. So in the statement

s[i]=str;

      

each element of the array of character pointers s gets the same address. You coudl change your code snippet in 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 is better written as a for loop

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

      

Also note that if your compiler supports Variable Length Arrays and s is a local variable of a function (for example, the main one), you can define it as follows.

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];

      

+3


source







All Articles