3

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!

2
  • 3
    n is 0 at start of for loop. also all of your strings will point at the last one scanned.. Commented Jul 5, 2015 at 12:31
  • 1
    char *s[5]; can hold five strings(char *). Commented Jul 5, 2015 at 12:33

2 Answers 2

4
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 */
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! Is it possible without dynamic allocation?
@Ravi yes use char s[6][MAX_STRING_LENGTH], but you still need strcpy or read directly in s[i]
@MohitJain don't you know about strdup()?
@HeathHunnicutt Yes strdup would work for unix type systems (Make sure to free at end). But you must note at the same time that it not part of the ISO C standard itself and is a POSIX extension.
@MohitJain of course it must be freed at the end, just like malloc(). I wasn't asking if it would work, I was pointing out that it's better.
|
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.