使用指针循环遍历数组 [英] Looping through array using pointers

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

问题描述

以下C ++程序输出的输出超出我的预期.谁能解释为什么会这样?该程序尝试使用指针遍历整数数组,并沿途打印每个值.

The following program in C++ prints more output than I expected. Can anyone explain why this has happened? The program attempts to use pointers to loop through the integer array, printing each value along the way.

#include <cstdio>
using namespace std;

int main(int argc, char **argv) {
    puts("hi");
    int ia[5] = {1,2,3,4,5};
    for (int *p = ia; *p; ++p) {
        printf("Char is: %d\n", *p);
    }
    return 0;
}

/*
 hi
 Char is: 1
 Char is: 2
 Char is: 3
 Char is: 4
 Char is: 5
 Char is: 32767
 Char is: -811990796
 Char is: -133728064
 Char is: 1606416320
 Char is: 32767
 Char is: -1052593579
 Char is: 32767
 Program ended with exit code: 0
*/

推荐答案

您将需要有一个0/NULL值才能停止,目前您不需要.

You will need to have a 0/NULL value to stop at, currently you do not.

您的循环条件将允许迭代,直到您得到一个计算结果为false(即0)且数组不包含该值的值,因此您的迭代将继续超出数组的边界,并在该点处退出访问一些它不应该使用的内存.

Your loop condition will allow iteration until you get a value that evaluates to false (i.e 0) and your array does not contain that, so your iteration will continue on past the bounds of the array and will at some point exit when it access some memory its not supposed to.

有几种方法可以修复它.您可以在数组的末尾添加0.

There are several ways to fix it. You can add a 0 to the end of the array.

#include <cstdio>
using namespace std;

int main(int argc, char **argv) {
    puts("hi");
    int ia[] = {1,2,3,4,5, 0};
    for (int *p = ia; *p; ++p) {
        printf("Char is: %d\n", *p);
    }
    return 0;
}

问题在于您现在不能在数组中使用0,否则它将提前终止.

Issue with this is that you now cant use 0 in your array, or it will terminate early.

给定数组长度,更好的方法是预先计算要停止的地址.该地址是数组末尾的地址.

A better way would be to pre calculate the address at which to stop, given the array length. This address is one off the end of the array.

#include <cstdio>
using namespace std;

int main(int argc, char **argv) {
    puts("hi");
    int ia[] = {1,2,3,4,5};
    int* end = ia + 5;
    for (int *p = ia; p != end; ++p) {
        printf("Char is: %d\n", *p);
    }
    return 0;
}

现在,我们正在走向标准库迭代器使用的方法.现在,模板可以推断出数组的大小.

Now we are getting towards the method used by standard library iterators. Now templates can deduce the size of the array.

#include <iterator>
...

for (auto it = std::begin(ia); it != std::end(ia); ++it) {
    printf("Char is: %d\n", *it);
}

...

最后,基于范围的还支持数组.

and finally, range based for also supports arrays.

for (auto i: ia)
{
    /* do something */
}

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

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