0

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 :

image

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 :

image

I know that this is undefined behavior, so is there any way to resolve this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Vjkaal
  • 3
  • 4
  • 4
    In the second example, the loop is looking for a zero value in the array. The `while` loop won't stop until it sees a 0. In the first example, all string literals have a terminating `nul` character which is 0. – Thomas Matthews Aug 23 '21 at 22:28
  • Change the expression in the `while` loop to compare by size, not by content. – Thomas Matthews Aug 23 '21 at 22:29
  • The first code doesn't even compile in C++. You can't assign a `char[]` to an `int*`. But even if it did compile, it would be printing `int` values, not `char` values. So the only way you could be getting `This is a String` as output is if you were using a `char*` instead of an `int*` – Remy Lebeau Aug 23 '21 at 22:56

1 Answers1

4
char str[] = "This is a String";
int *p = str;

This program is ill-formed. char[N] does not implicitly convert to int* in C++, only to char*.


int arr[] = {1,2,3,4,5,6,7,8,9};
int *p = arr;
while(*p) std::cout<<*p++<<" ";

I know that this is undefined behavior

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.

is there any way to resolve this.

Sure. Just don't access beyond the bounds of the array.

A good choice is to use a range-for loop:

for(int i : arr) {
    std::cout << i << ' ';
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
eerorika
  • 232,697
  • 12
  • 197
  • 326