Question

There is something wrong with the code below... Could someone explain to me whats the problem and why?

#include<stdio.h>

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

 int main()
 {
  int d;

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

  return 0;
}
Was it helpful?

Solution 2

The sizeof operator: ...

"The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in < stddef.h > (and other headers)." - C99 standard.

Conversions: ...

"Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type." - C99 standard.

The int d(-1) is converted to (TOTAL_ELEMENTS-2) type which is sizeof return type(an unsigned integer). This is usually done by reinterpreting the bits as an unsigned value => -1 signed integer = 0xFFFFFFFF(if int has 32 bits) unsigned integer.

You are trying to compare 0xFFFFFFFF with 0x5(TOTAL_ELEMENTS-2) which is false.

You should have a warning... signed/unsigned mismatch...

C99 standard

OTHER TIPS

Usual arithmetic conversions.

In the <= expression the int value -1 is converted to the unsigned type of sizeof and becomes a huge value and the <= expression is then false.

Use:

for(d=-1;d <= (int) (TOTAL_ELEMENTS-2);d++)

Please find the below changes

#include

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

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

  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top