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?

3
  • 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. Commented Aug 23, 2021 at 22:28
  • Change the expression in the while loop to compare by size, not by content. Commented Aug 23, 2021 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* Commented Aug 23, 2021 at 22:56

1 Answer 1

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 << ' ';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.