What causes the array in the following code not to be printed?

半腔热情 提交于 2020-01-15 12:27:29

问题


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;
}

回答1:


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




回答2:


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++)



回答3:


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;
}


来源:https://stackoverflow.com/questions/16981790/what-causes-the-array-in-the-following-code-not-to-be-printed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!