这是处理C多维数组导航的正确方法吗?

时间:2013-08-24 17:57:01

标签: c pointers

我担心的是我计算td结束的方式是正确的。这是最佳的吗?是否有更好的C语言来做这类事情?

#include <stdio.h>

int main() {

    char td[][4] = { {0,1,2,3}, {4,5,6,7}, {8,9,10,11}, 
                      {12,13,14,15}, {16,17,18,19}, {20,21,22,23}  };
    char* p = *td;  

    int rows = sizeof(td) / sizeof(td[0]);
    int cols = sizeof(td[0]) / sizeof(td[0][0]);

    char* end = p + (rows * cols);

    /* Print first element in each 'row' */
    while(p != end) {
        printf("first element: %u\n", p[0]);
        p += 4;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:2)

通常会在C中使用for循环。

int main() {
    char td[][4] = { {0,1,2,3}, {4,5,6,7}, {8,9,10,11}, 
                      {12,13,14,15}, {16,17,18,19}, {20,21,22,23}  };

    int rows = sizeof(td) / sizeof(td[0]);
    int cols = sizeof(td[0]) / sizeof(td[0][0]);

    /* Print first element in each 'row' */
    for (int row = 0; row < rows; row++)
        printf("first element: %u\n", td[row][0]);

    return 0;
}

但是,您编写的代码确实有用。

答案 1 :(得分:1)

#define COLS 4
int main() {
    char td[][COLS] = { {0,1,2,3}, {4,5,6,7}, {8,9,10,11}, 
                      {12,13,14,15}, {16,17,18,19}, {20,21,22,23}  };

    int rows = sizeof(td) / sizeof(td[0]);

    /* print the matrix */
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < COLS; col++) {
            printf("first element: %u\n", td[row][col]);
        }
    }
    return 0;
}

对于每行的第一列:

    for (int row = 0; row < rows; row++) {
        printf("first element: %u\n", td[row][0]);
    }