1

what is wrong with this code ? can anyone explain ?

#include <stdio.h>
#include <malloc.h>

#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
  int array[] = {23,34,12,17,204,99,16};

  int main()
  {
      int num;
      int d;
      int size = TOTAL_ELEMENTS -2;
      printf("%d\n",(TOTAL_ELEMENTS-2));

      for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
          printf("%d\n",array[d+1]);

      return 0;
  }

when i print it gives 5, but inside for loop what is happening ?

2 Answers 2

5

The sizeof operator returns a value of type size_t, which is an unsigned value. In your for loop condition test:

d <= (TOTAL_ELEMENTS-2)

you are comparing a signed value (d) with an unsigned value (TOTAL_ELEMENTS-2). This is usually a warning condition, and you should turn up the warning level on your compiler so you'll properly get a warning message.

The compiler can only generate code for either a signed or an unsigned comparison, and in this case the comparison is unsigned. The integer value in d is converted to an unsigned value, which on a 2's complement architecture ends up being 0xFFFFFFFF or similar. This is not less than your TOTAL_ELEMENTS-2 value, so the comparison is false.

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

1 Comment

2s complement is irrevelant - (size_t)-1 is always SIZE_MAX.
-1

You're starting the loop by setting d = -1, it should be d = 0. So for the first element you're reading random bits of memory.

If you fix that, then you can change your printf to be

printf("%d\n",array[d]);

As you've also marked this as homework, I'd advise also take a look at your loop terminating condition.

2 Comments

but array[d+1] gets printed, so what's wrong ? this is not reading random bits, since loop terminates immediately
i didn't, but see above explanation by Greg

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.