Thursday, July 9, 2009

Simple C++ Array Question?

I'm having a lot of trouble populating a very simple, 2 dimensional array. What I want this program to output is:





xx


bb





However, what I get when I compile and execute it is





xx


bbb





I don't understand it. Here's my program:





char smile2[2][2] = {{'x', 'x'},


{'b', 'b'}};





for (int row = 0; row %26lt;3; ++row)


for (int column=0; column%26lt;3; ++column)


{


if (column ==2)


cout%26lt;%26lt;endl;


cout%26lt;%26lt;smile2[row][column];





}





As you can see, it's very simple. Also, I hardcoded the array, and there are two b's in there, not three. I don't understand how the third one gets in there.





Any ideas?

Simple C++ Array Question?
The problem is in how you set up your for loops. Remember that arrays begin their indexes at 0 so you only have elements in the 0 and 1 positions. The problem is, you are outputting the smile2[0][2] position after the first endl.





Here's a more efficient way to write this process (the only changes are to the for loops):





for (int row = 0; row %26lt; 2; row++)


{


for (int column = 0; column %26lt; 2; column++)


{


cout %26lt;%26lt; smile2[row][column];


}


cout %26lt;%26lt; endl;


}





Basically the problem was that when you were accessing members of the array it was going beyond where the actual array was. When memory was allocated for your array, the positions for the second row were right after the positions for the first. So, in memory it kindof looked like this:


(some junk here) x x b b (more junk)








Hopoe that helps!
Reply:Try this





for (int row = 0; row %26lt;2; row++)


{


for (int column=0; column%26lt;2; column++)


{


cout%26lt;%26lt;smile2[row][column];


if (column == 1) cout%26lt;%26lt;endl;


}


}





The Data Analyst - http://www.squidoo.com/thedataanalyst
Reply:I think you have missed out something in this... I also cannot seem to get the answer right.
Reply:Bad indexing. You array in both dimensions has a limit of 2. Hence, you can only refer to the indices 0 and 1.





Look at your for loops. row=0 is valid, row= 1 is valid, and row=2 is valid (row %26lt; 3). The same is true of column. It's only dumb luck (and that the array was allocated contiguously) that you have three bs printing out. You could end up with a segfault because you are accessing invalid memory locations.





Also, there is no need for if (column == 2). Look, you have two for loops. Everytime you finish printing out a column, you output a newline. Hence all you need is





for (....) //loop for row


{





for (...)


{


// column stuff


}








std::cout %26lt;%26lt; "\n";





}


No comments:

Post a Comment