chararray遍历_使用指针循环遍历数组

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

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

*/

解决方案

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

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.

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

#include

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;

}

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

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.

i.e.

#include

...

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 */

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值