2D array removes its elements after exiting the loop
2D array removes its elements after exiting the loop
Input is: hello world
The following program should record "hello" in words[0] and "world in words[1]
int rowIndex= 0;
char words [100][100];
for (int x = 0 ; x < input.length(); x++)
{
if (input[x]>='a'&&input[x]<='z' || input[x]>='A'&&input[x]<='Z')
// This condition is to avoid recording spaces in the array
{
words[rowIndex][x]= input[x];
cout << words[rowIndex][x]<<" ";
}
else {
rowIndex++;
// Once it finds a space, it records the following characters into the next index
cout << " Index: " << rowIndex <<endl;
}
}
output:
h e l l o
Index: 1
w o r l d
cout <<"Index 0: "<< words[0] <<endl;
Output: hello
cout <<"Index 1: "<< words[1] <<endl;
Output: " doesn't output anything" ( Why doesn't it output "world")
*****************************************************
Why doesn't the array hold the characters in words[1] and only holds the characters in words[0]
Note: I tried doing it with dynamic 2D array and same problem happened.
x
1 Answer
1
cout <<"Index 1: "<< words[1]
exhibits undefined behavior, by way of accessing words[1][0]
that was never initialized.
cout <<"Index 1: "<< words[1]
words[1][0]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You don't reset
x
on a new word.– Johnny Mopp
Jun 29 at 21:53