I am writing a simple console application to read 3 words and keep them in an array. But after taking three inputs from the console it only displays the third word three times in the console. For example, if I give the input: “one”, “two” “three” the output shows only “three” 3 times).
Here is my code:
int main(int argc, char *argv[])
{
char* input[30];
char word[30];
int i=0;
for(i=0; i<3 ;++i)
{
cin >> word;
input[i] = word;
}
input[i] = 0;
i=0;
while(input[i])
{
cout << input[i] << endl;
i++;
}
return 0;
}
What I am doing wrong here? Thanks for any help.
You only have one buffer (
char word[30]), which you are overwriting each time.When you do:
You’re assigning the address of the first element in that one and only buffer to each element in
input(arrays degrade to pointers when you use the bare name). You end up with three copies of the same address ininput[](which is address ofword, which contains the last thing your read fromcin)One approach to fix this would be to use
strdup()and assign the newly allocated string to yourinput[i]Also … if you only are going to have three input “words” you only need an array of 3
charpointers:and your output loop would look much like your input loop:
Edit: Note that this answer was based on your wanting to use arrays. If this isn’t homework that requires that, see bobbymcr’s answer – when in C++, use C++.