1

I'm very new to programming in C and I'm trying to print an array of strings. I can enter the input easily enough but then when it tries to print the array the program stops responding. Any help is appreciated, thanks.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
int a, b;
char answer[256];

for(a=1; a<=20; a++)
{
    scanf("%s", &answer[a]);
}

for(b=1; b<=20; b++)
{
    printf("%s\n", answer[b]);
}
}

Update: Thanks for all the fast replies everyone, the program is running smoothly now!

2
  • 3
    that's not an array of strings but an array of characters. please read your textbook for clarification. Commented May 18, 2015 at 16:44
  • you don't have an array of strings, but an array of char. so it looks like you are only reading in the first char of each string you are trying to read Commented May 18, 2015 at 16:45

3 Answers 3

5
int a, b;
char answer[20][256];//<- array of char[256]

for(a=0; a<20; a++)//<- 0 origin
{
    scanf("%255s", answer[a]);//<- Reading of the string with a maximum 255 characters (One is reserved for the termination character('\0'))
}

for(b=0; b<20; b++)
{
    printf("%s\n", answer[b]);
}
Sign up to request clarification or add additional context in comments.

Comments

4

1)

char answer[256];

is an array of chars, not strings. With the way, you wrote the rest of the code, you would need an array of arrays such as:

char answer[100][256];

2) scanf() expects char* for the format string %s. So you would only need:

scanf("%s", answer[a]);

3) main() should return int. So it should be: int main(void) or equivalent.

4) Another problem you have likely got wrong (looking at your loops) is that indexing in C is zero-based, not starts from 1.

Comments

1

Using

char answer[256];

you get only an array of characters, which can be used to store a string. To store an array of strings, use:

char answer[20][256];

That can be used to store 20 strings as long as none of those strings is longer than 255 characters.

void main()
{
   int a, b;
   char answer[20][256];

   ///////////////////////////////////////////
   // Notice the difference in the value of a.
   ///////////////////////////////////////////
   for(a=0; a<20; a++)
   {
      scanf("%s", answer[a]);
   }

   for(b=0; b<20; b++)
   {
      printf("%s\n", answer[b]);
   }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.