应该使用哪种类型循环遍历数组? [英] What type should be used to loop through an array?

查看:113
本文介绍了应该使用哪种类型循环遍历数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们拥有这个数组:

char arr[SIZE_MAX];

我想遍历它(以及最后一个元素之后的一个):

And I want to loop through it (and one past its last element):

char *x;

for (i = 0; i <= sizeof(arr); i++)
        x = &arr[i];

(编辑后添加了一些带有指针的有效代码).

(Edited to add some valid code with pointers).

i最合适的类型是什么?

What is the most adequate type for i?

我接受非标准类型,例如POSIX的类型.

I accept non-standard types such as POSIX's types.

相关问题:

将sizeof()的结果分配给ssize_t

推荐答案

嗯,有趣的情况.您希望能够循环使用,假设我们仅将其称为可能的最大数字,从而进行环绕,而不是使比较返回false.这样的事情可能会解决问题:

Hmm, interesting case. You want to be able to loop with, let's just call it hypothetically the largest possible number, and thus wrap-around rather than ever having the comparison return false. Something like this might do the trick:

char arr[SIZE_MAX];
size_t i = 0;
do {
    /* whatever you wanna do here */
    ++i;
}
while (i <= sizeof(arr) && i != 0);

由于do-while将始终执行第一次迭代,因此我们可以设置一个条件,使循环在i == 0时结束,并且仅在回绕到0而不是第一次迭代时才会发生.为i <= sizeof(arr)添加另一个条件,以处理我们没有回绕的情况.

Because a do-while will always perform the first iteration, we can put a condition such that the loop will end when i == 0, and it will only happen upon wrapping back around to 0 rather than on the first iteration. Add another condition for i <= sizeof(arr) to take care of cases where we don't have wrap-around.

这篇关于应该使用哪种类型循环遍历数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆