peeyush
peeyush

Reputation: 2931

c code output unexpected/expected behaviour

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 ?

Upvotes: 1

Views: 99

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 994727

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.

Upvotes: 5

DaV
DaV

Reputation: 764

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.

Upvotes: -1

Related Questions