for loop in objective-c - primitive array


for loop in objective-c - primitive array



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()?




Weird Objective-C Mod Behavior for Negative Numbers

1:



When should I remove observers? Error about deallocating objects before removing observers
For statically created array types, you can use the sizeof operator, e.g..
Are ints always initialized to 0?
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).


How can I keep an NSPopUpButton open after the user selects a menu item?
In this case, you need either constants, or a sentinal value in your array.


Setting value of instance variable dynamically
With a sentinal, just scan each axis until you find it for the length (this is how C strings work, using \0)..
Static constructor equivalent in Objective-C?


Comparing dates


Objective C NSString problem

2:


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 ~ $ 


3:


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.

.


4:


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       }  } 



86 out of 100 based on 66 user ratings 1166 reviews