0

我担心的是我计算 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;
}
4

2 回答 2

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

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

于 2013-08-24T18:00:54.177 回答
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]);
    }
于 2013-08-24T18:04:43.693 回答