Click here to Skip to main content
15,888,014 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I've got this task that requires reading 4-character strings from standard input into an array. I tried one way but every time i tried printing any element of this array it always printed the last one from input. For instance input:
abcd
dcba
aaaa
...
zzzz (the 20th string)

printf("%s",arrayString[3]);

Output:
zzzz

Could anyone explain why is it working the way it is?

What I have tried:

char *stringArray[20];
char temp[4];
int i;
for(i=0;i<20;i++){
    scanf("%s",temp);
    stringArray[i]=temp;
    }
Posted
Updated 19-Nov-17 12:18pm

1 solution

You have an array of 20 string pointers.
Each of these points to the same memory (temp).
Because that is used for reading the user input within a loop, it contains the last input string.

You can use a two-dimensional array instead:
C++
char stringArray[20][5];
int i;
for (i=0;i<20;i++)
{
    scanf("%4s", stringArray[i]);
}
Note that I have increased the input string size (there must be always one more character to store the terminating NULL byte) and added that limit also to the scanf format string.
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 20-Nov-17 3:21am    
5ed.
Member 13478986 20-Nov-17 12:28pm    
thanks!much appreciated

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900