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?


whileloop won't stop until it sees a 0. In the first example, all string literals have a terminatingnulcharacter which is 0.whileloop to compare by size, not by content.char[]to anint*. But even if it did compile, it would be printingintvalues, notcharvalues. So the only way you could be gettingThis is a Stringas output is if you were using achar*instead of anint*