views:

7416

answers:

4

int matrix[3][3] = { {1,2,3}, {1,2,3}, {1,2,3}, }

how can i loop over it? basically the length operation is my concern.

for (int i=0; XXXXX; i++) { for (int j=0; XXXX; j++) { int value = matrix[i][j]; } }

EDIT: is there a dynamic way of getting the array size? something like sizeof() thank you, chris

A: 

You can do this just as you would in C:

int matrix[3][3] = { {1,2,3}, {1,2,3}, {1,2,3}, };

for(int i = 0; i < 3; i++)
{
    for(int j = 0; j < 3; j++)
    {
        int value = matrix[i][j];
    }
}

Though, I recommend using a constant instead of magic 3's. Will make everything more readable, especially the for loop.

Sean
yes its working if you set the condition to X < 3but isn`t there a dynamic approach? a sizeof or something?
Are you using Objective-C for Cocoa? If so you can use an NSArray or NSMutableArray and then you can use myArray.Count. http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSArray_Class/Reference/Reference.html
Sean
the problem with hard coding 3 in the loop, is when someone adds another element to the matrix, the sizeof() conventions are used to not have to rewrite all coded sizes, when that happens.
sfossen
A: 

The length of the top level array is 3, the length of each sub array is 3, so this should work:

for( int i = 0; i < 3; ++i ) {
      for( int j = 0; j < 3; ++j ) {
           // do something here for each element
      }
 }
drewh
++i => i++++j => j++
editor
+3  A: 

For statically created array types, you can use the sizeof operator, e.g.

sizeof(myArray) / sizeof(myArray[0])

For dynamically created arrays (i.e referened by pointer), this won't work (sizeof will just give you the size of a pointer on your system). In this case, you need either constants, or a sentinal value in your array. With a sentinal, just scan each axis until you find it for the length (this is how C strings work, using \0).

Adam Wright
+3  A: 

In C I'd do the following, try:

sizeof( matrix ) /sizeof( matrix[0] )         <- outer array
sizeof( matrix[0] )/ sizeof( matrix[0][0] )   <- inner array



linux ~ $ cat sizeof_test.c
#include <stdio.h>

int main( void )
{
        int matrix[][3] = { {1,2,3}, {1,2,3}, {1,2,3}, };
        int matrix2[][3] = { {1,2,3}, {1,2,3}, {1,2,3}, {1,2,3}, };
        int matrix3[][4] = { {1,2,3,4}, {1,2,3,4}, {1,2,3,4}, {1,2,3,4}, };

        printf( "array (%d) - elements( %d )\n", sizeof( matrix ) /sizeof( matrix[0] ), sizeof( matrix[0] )/ sizeof( matrix[0][0] ));
        printf( "array (%d) - elements( %d )\n", sizeof( matrix2 ) /sizeof( matrix2[0] ), sizeof( matrix2[0] )/ sizeof( matrix2[0][0] ));
        printf( "array (%d) - elements( %d )\n", sizeof( matrix3 ) /sizeof( matrix3[0] ), sizeof( matrix3[0] )/ sizeof( matrix3[0][0] ));

        return 0;
}
linux ~ $ gcc sizeof_test.c -o sizeof_test
linux ~ $ ./sizeof_test
array (3) - elements( 3 )
array (4) - elements( 3 )
array (4) - elements( 4 )
linux ~ $
sfossen