Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through array using pointers

Tags:

c++

pointers

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
*/
like image 212
none Avatar asked Nov 30 '22 09:11

none


1 Answers

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

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.

i.e.

#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 */
}
like image 138
Paul Rooney Avatar answered Dec 05 '22 18:12

Paul Rooney