I referred this link Pointer expressions: *ptr++, *++ptr and ++*ptr to understand pointer arithmetic.
Why the below code is going to infinite loop?
int main(){
int a[4] ={1,2,3,4};
int *ptr = a;
while (++*ptr){
printf("%d",*ptr);
}
}
I referred this link Pointer expressions: *ptr++, *++ptr and ++*ptr to understand pointer arithmetic.
Why the below code is going to infinite loop?
int main(){
int a[4] ={1,2,3,4};
int *ptr = a;
while (++*ptr){
printf("%d",*ptr);
}
}
Your code does not work for two reasons:
++*ptr
increments the number, not the pointerYou can iterate a C string using while (*ptr++)
expression for the loop condition. This little trick works for C strings because they are null terminated. In order to make it work for arrays you would need to put zero at the end of the array, and agree to not use zeros anywhere else in the array:
int a[4] ={1,2,3,4, 0};
int *ptr = a;
int last;
while (last = *ptr++) {
printf("%d", last);
}
Note that since we are incrementing the pointer in the header of the loop, we should store the last value pointed to by the pointer in a separate variable. Otherwise we'd skip over one array element.
in loop condition value is 0 that time only loop terminated but you just increment the first position of the array value so zero value will not occur.
The issue is in the following line. Your while will break only if the value of ++*ptr is false or 0. But it never becomes 0 or false.
++*ptr
so while(NON ZERO) will result in infinite loop.
The loop is "infinite" because the condition in the while statement is always true until you hit the maximum value int
can hold and after that you get undefined behavior.
What happens in the line is:
while (++*ptr)
First the pointer is dereferenced *ptr
, obtaining the value of the first element in the array a
, then that value is incremented by one. And then that resulting value is evaluated, giving the true result.
The same happens on every loop, the pointer ptr
keeps pointing to the same element, the first one ptr == &a[0]
, and keeps incrementing the value of that element by one a[0] = a[0]+1
.
You are incrementing the value of the corresponding 0th position. So the starting position value of array is incremented. So the loop executing infinitely. Make the while loop as following.
while(*(++ptr))