I was learning about pointers and pointers to arrays, when I encountered this strange thing.
Can anyone explain why this works?
char str[] = "This is a String";
int *p = str;
while(*p) std::cout<<*p++;
and returns :
but this one generates a nasty error:
int arr[] = {1,2,3,4,5,6,7,8,9};
int *p = arr;
while(*p) std::cout<<*p++<<" ";
like this :
I know that this is undefined behavior, so is there any way to resolve this?
This program is ill-formed.
char[N]
does not implicitly convert toint*
in C++, only tochar*
.Do you understand why it is undefined behaviour? The problem is that the condition to end your loop is when you reach the element with value 0. But you didn't put any zeroes in your array, so the loop never stops and you access beyond the end of the array.
Sure. Just don't access beyond the bounds of the array.
A good choice is to use a range-for loop: