0

I don't quite understand why when I run the code, inputting with 5 different strings, it prints string[0] as the last string that I enter:

for example, if I input:

yes
no

it would print:


Check yes
yes
yes
Check no
no
no

even for index=0

int main(void) {
   char *string[5];
   char entered[11];
   for(int j = 0; j < 5; j++) {
     scanf("%s", &entered);
     string[j] = entered;
     printf("Check %s\n",entered);    
     printf("%s\n",string[j]); 
     printf("%s\n",string[0]); 
       }
   return 0;
 }

My intention is to save each string entry into the array.

So for my example, I want:


Check yes
yes
yes
Check no
no
yes

I am not allowed to use malloc...etc.

1
  • Increase the warning level of your compiler, and mind the warnings. Commented Mar 24, 2012 at 12:18

1 Answer 1

2

This line:

     string[j] = entered;

does not copy characters from entered to string[j]; rather, it sets string[j] to point to the memory location of the entered array.

You need to allocate memory for the strings in your string array, by writing (e.g.):

char string[5][11];

instead of

char *string[5];

and then you need to copy characters from entered from string[j] by writing (e.g.):

     strcmp(string[j], entered);
Sign up to request clarification or add additional context in comments.

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.