C: Size of two dimensional array

后端 未结 5 1863
无人共我
无人共我 2021-02-12 09:37

I need some help counting the rows and columns of a two dimensional array. It seems like I can\'t count columns?

#include 

int main() {

char res         


        
5条回答
  •  隐瞒了意图╮
    2021-02-12 10:26

    This works for me (comments explains why):

    #include 
    
    int main() {
    
       char result[10][7] = {
    
           {'1','X','2','X','2','1','1'},
           {'X','1','1','2','2','1','1'},
           {'X','1','1','2','2','1','1'},
           {'1','X','2','X','2','2','2'},
           {'1','X','1','X','1','X','2'},
           {'1','X','2','X','2','1','1'},
           {'1','X','2','2','1','X','1'},
           {'1','X','2','X','2','1','X'},
           {'1','1','1','X','2','2','1'},
           {'1','X','2','X','2','1','1'}
    
       }; 
    
       // 'total' will be 70 = 10 * 7
       int total = sizeof(result);
    
       // 'column' will be 7 = size of first row
       int column = sizeof(result[0]);
    
       // 'row' will be 10 = 70 / 7
       int row = total / column;
    
       printf("Total fields: %d\n", total);
       printf("Number of rows: %d\n", row);
       printf("Number of columns: %d\n", column);
    
    }
    

    And the output of this is:

    Total of fields: 70
    Number of rows: 10
    Number of columns: 7
    

    EDIT:

    As pointed by @AnorZaken, passing the array to a function as a parameter and printing the result of sizeof on it, will output another total. This is because when you pass an array as argument (not a pointer to it), C will pass it as copy and will apply some C magic in between, so you are not passing exactly the same as you think you are. To be sure about what you are doing and to avoid some extra CPU work and memory consumption, it's better to pass arrays and objects by reference (using pointers). So you can use something like this, with same results as original:

    #include 
    
    void foo(char (*result)[10][7])
    {
       // 'total' will be 70 = 10 * 7
       int total = sizeof(*result);
    
       // 'column' will be 7 = size of first row
       int column = sizeof((*result)[0]);
    
       // 'row' will be 10 = 70 / 7
       int row = total / column;
    
       printf("Total fields: %d\n", total);
       printf("Number of rows: %d\n", row);
       printf("Number of columns: %d\n", column);
    
    }
    
    int main(void) {
    
       char result[10][7] = {
    
           {'1','X','2','X','2','1','1'},
           {'X','1','1','2','2','1','1'},
           {'X','1','1','2','2','1','1'},
           {'1','X','2','X','2','2','2'},
           {'1','X','1','X','1','X','2'},
           {'1','X','2','X','2','1','1'},
           {'1','X','2','2','1','X','1'},
           {'1','X','2','X','2','1','X'},
           {'1','1','1','X','2','2','1'},
           {'1','X','2','X','2','1','1'}
    
       };
    
       foo(&result);
    
       return 0;
    }
    

提交回复
热议问题