Indexing an integer pointer in C ++

I start in C ++ and try to make out every new concept that I come across when writing as many different small programs (programmers) as possible. So I just came up with the following code snippet:

#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 don’t understand the seemingly simple thing: how does the compiler “know” when to stop increasing the loop variable “i”? Surprisingly, the code really works as intended.

+4
source share
5 answers

The compiler does not know when to stop.

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

, p[i] 0. , p[5] 0. , , . i >= array size , , undefined .

, 0

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

1
2

.

, ,

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

. const & , int, , const .

,

for (int i = 0; i < size_of_pointed_to_array, i++)
    std::cout << p[i] << '\n';
+10

. , , inumbers .

. , :

for(i = 0; i < sizeof(inumbers)/sizeof(int); i++) cout << p[i] << '\n';
+3

undefined. , , , p[i] false, , p[i] == 0.

++

, 0, 4 4 , 0. , 0.

0, .

i .

+2

undefined.

, . , ( ). ( for while p[i] is non-zero).

undefined, ++ . "" - , .

+2

. , p [i], 5, false 0. , 0 , .

+1

All Articles