2

I am a newbie and am trying to understand the concept of pointers to an array using the example below. Can anyone tell me what the exit condition for the loop should be?
The while loop seems to be running forever but the program terminates with no output.
Thank you.

typedef struct abc{
    int a;
    char b;
} ABC;

ABC *ptr, arr[10];

int main()
{
    ptr = &arr[0];
    int i;
    for(i = 0; i < 10; i++){
        arr[i].a = i;
    }
    while(ptr!=NULL){
        printf("%d \n", ptr->a);
        ptr++; //Can I use ptr = ptr + n to skip n elements for some n?
    }
}
4
  • 1
    How does the program terminate if you have an infinite loop? Commented Sep 22, 2013 at 15:38
  • I am quite sure ptr!=NULL does not work. How to make this work? I am not sure what the loop exit condition should be. Commented Sep 22, 2013 at 15:40
  • There's no end to incrementing a pointer, unless it happens to loop back to zero when it overflows. Commented Sep 22, 2013 at 15:40
  • The ptr!=NULL condition is very often used in strings, where you have a null-terminator as part of the convention. In arrays it does not apply. Commented Sep 22, 2013 at 15:45

2 Answers 2

2
while(ptr!=NULL){

This will run until ptr becomes NULL. Since it points to the first element of the array, and it's always incremented, and we don't know any other implementation detail, it may or may not become NULL. That's not how you check for walking past the end of the array. You would need

while (ptr < arr + 10)

instead.

Can I use ptr = ptr + n to skip n elements for some n?

Of course. And while we are at it: why not ptr += n?

Sign up to request clarification or add additional context in comments.

Comments

0

The loop isn't infinite, it stops when ptr == 0. Assuming you have a 32bit computer, ptr is 32 bits wide. SO it can hold numbers from 0 to 4294967296-1 (0 to 2 ^ 32 -1). Each time through the loop it adds 8 to ptr. Eventually ptr will get to be 4294967296-8. Adding 8 to that results in 4294967296 - but that is an overflow so the actual result is 0.

Note: This only works if PTR happens to start at a multiple of 8. Offset it by 4 and this would be an infinite loop.

CHange the printf from "%d" to "%x" - printing the numbers in hex will make it more clear I think.

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.