I’m stuck with the following while loop.
whille(*rtn)
is considered false as long as the first value is zero (see example 0 below) so the program doesn’t enter the while loop. If I change the first value to be non zero (example 1) the program will enter the while loop. If I change the value assignment so that the fifth element will be zero (example 2) the while loop will stop at the fifth element. The for loop works as expected.
size_t sz = 100 ;
int *rtn = malloc(sz*sizeof(int));
int cnt ;
for(cnt = 0 ; cnt < sz ; cnt++){
EXAMPLE 0 rtn[cnt] = cnt*2 ; // First value of array is 0
EXAMPLE 1 rtn[cnt] = cnt*2 + 5 ; // first value of array is non zero
EXAMPLE 2 rtn[cnt] = 5 - cnt ; // fifth value will be 0
}
cnt=0 ;
printf("n---WHILE LOOP---n") ;
while(*rtn){
printf("%3d - %4dn",cnt, *rtn) ;
cnt++ ;
rtn++ ;
}
printf("n---FOR LOOP---n") ;
for(cnt = 0 ; cnt < 10 ; cnt ++){
printf("%3d - %4dn", cnt, rtn[cnt]) ;
}
I thought the while loop is testing for the NULL pointer not for 0 which obviously can be a valid value!?
Also if i change the while loop to
while(rtn){
...
}
it will just go through the complete memory (?) and end with an error. So in essence the while loop is not a valid tool to iterate through an int array?!