gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:56 25 4
gpt4 key购买 nike

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

最佳答案

人们通常会在 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;
}

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

关于c - 这是处理C多维数组导航的正确方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18421512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com