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