Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexing an integer pointer in C++

Tags:

c++

I'm a beginner in C++ and trying to get my head around every new concept I come across by writting as many various little programs (programmlets) as possible. So I've just concocted the following piece of code:

#include <iostream>
using namespace std;

int main(){
int inumbers[] = {1 ,2 , 3, 4, 5};
int *p;
int i;

p = inumbers;

for(i = 0; p[i]; i++) cout << p[i] << '\n';

return 0;

}

And I fail to understand a seemingly simple thing: how does a compiler "know" when to stop incrementing the loop variable "i"? Surprisingly, the code does work the way it was supposed to.

like image 792
Albert Avatar asked Dec 01 '22 13:12

Albert


2 Answers

The compiler does not know when to stop.

for(i = 0; p[i]; i++)

will only stop when p[i] is 0. You just got lucky and p[5] happened to be 0. There is nothing saying that it has to be so and it could keep going like this example. As soon as i >= array size you are accessing memory the array does not own and you enter the world of undefined behavior.

Also if you had a 0 in the array like

int inumbers[] = {1 ,2 , 0, 4, 5};

then the program will only print

1
2

And it will not visit the rest of the array.

When dealing with an array or a standard container you can use a ranged based for loop like

for (const auto & e : inumbers)
    std::cout << e << '\n';

To iterate through it's contents. Then const & is not really needed in this case as we are dealing with an int but it is a good habit to get into as passing by reference avoids copying and making it const prevents you from accidentally modifying the element when doing a read only operation.

When dealing with a pointer you need to provide a size like

for (int i = 0; i < size_of_pointed_to_array, i++)
    std::cout << p[i] << '\n';
like image 79
NathanOliver Avatar answered Dec 08 '22 00:12

NathanOliver


You got lucky. By random chance, it appears that there was a zero in memory after the last element in your inumbers array.

Your program is not actually correct. Instead, you might want to limit your loop by counting array members:

for(i = 0; i < sizeof(inumbers)/sizeof(int); i++) cout << p[i] << '\n';
like image 40
Logicrat Avatar answered Dec 08 '22 00:12

Logicrat