-
Newby array problem
Hi,
I have never done anything with multi dimensinal arrays before, and got stuck with a simple code, what's supposed to fill array "Table" with zeros. I keep getting error: error C2059: syntax error : '['
I'd be greateful, if sb told me, what's wroing with it.
Code:
int Table[12][12];
for ( int a = 0; a < 12; a++ ) {
for ( int b = 0; b < 12; b++ ) {
Table[a][b] = [0][0];
}
}
-
you're not assigning right, just change the [0][0] to 0.
Code:
int Table[12][12];
for ( int a = 0; a < 12; a++ ) {
for ( int b = 0; b < 12; b++ ) {
[b]Table[a] = 0; //nothing special here, just a regular assignment
}
}
another shortcut would be to do this:
Code:
int Table[12][12]={0};
That initializes the entire array of arrays to zero.
-
-
Here is an easier way to initialize an array:
Code:
int Table[12][12] = {0};
When you use an initializer list, which is what is on the right hand side, and you don't specify all the values for each index position, then the positions you don't specify will be initialized with 0. So, all you have to do is specify 0 for the first element in the array, and since the rest of the elements aren't specified, they will be initialized with 0.
-
thanks for reading my post ;)
-
Thanx for all the answers, but I have one more question: Is there something like .length value in Java? I tryed sizeof() But it just repeats the action 12x12 times, when used in loop. :p
-
not really, if you're using C-style strings, you could use strlen(char*) from the <cstring> header.
-
In C++, you would generally use the standard vector class for this purpose. That class has a length() method. The syntax might look odd at first, but vectors are easier and safer in the long run than regular C style arrays. This is the equivalent to a 12x12 int array initialized to 0:
Code:
std::vector<std::vector<int> > Table(12, std::vector<int>(12));