Look at this code:
#include "stdafx.h"
#include %26lt;iostream%26gt;
#include %26lt;cstdlib%26gt;
using namespace std;
int playerGrid[7][7] = { {0},{0} };
int computerGrid[7][7] = { {0},{0} };
void clrgrids()
{
playerGrid[7][7] = { {0},{0} };
computerGrid[7][7] = { {0},{0} };
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
When I first declare the arrays and set their values to 0, it works fine. But when I try to do the same thing in a function, it gives me an error. What gives?
C++ arrays?
Without knowing what the error is, my guess is this:
Since the function has a different scope, it thinks you're trying to define new arrays with that name, local to the function. The problem is you don't specify what type of new array. (In this case, you don't include the 'int' before it.) Get what I'm saying? It's not referring to the original arrays you initialized.
To access and change the original arrays, you'd have to pass them by reference as arguments to the function.
Reply:the way in which u r giving the value to the array is valid only at declaration time not during assignment
Reply:There are (at least) 2 problems in the clrgrids() function.
This applies to both lines in the function, so I will only discuss the first line (playerGrid[7][7] = { {0}, {0} };)
1. Literal array syntax -{ {0}, {0} } - is used when you want to assign to the ENTIRE array. However, assignment to the ENTIRE array is only allowed if you initialize it when you declare it. After the array is declared, you can only assign to an individual element. Also, you are trying to assign to an individual element here. playerGrid[7][7] is ONE element, so trying to assign an array to a single element of the array will not work.
2. playerGrid[7][7] - these subscripts are too large. You declared the array as [7][7], which gives you 7 arrays of 7 elements each. So, you have subscripts [0][0] through [6][6].
If you were to change the line to:
playerGrid[7][7] = 0; //assign a single value to a single element
the code MIGHT compile. Depending on your compiler/system, it MIGHT run without an obvious error. However, when you assign to playerGrid[7][7], you are overwriting memory that is not a part of the playerGrid array. You will be overwriting other data used by your program, or potentially memory belonging to another program. On most systems, this will generate an access violation.
To fix both problems, change your clrgrids() function to assign 0 to each element of the array. Use two nested for loops to step through the array, like so:
void clrgrids()
{
for (int row = 0; row %26lt; 7; row++)
for (int col = 0; col %26lt; 7; col++)
{
playerGrid[row][col] = 0;
computerGrid[row][col] = 0;
}
}
For more information on C++ arrays, see:
http://www.fredosaurus.com/notes-cpp/arr...
http://www.cplusplus.com/doc/tutorial/ar...
secret garden
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment