sizeof behaving unexpectedly

前端 未结 4 1050
再見小時候
再見小時候 2021-01-04 09:02

Consider the following code:

  #include 
  int main(void)
  {
    int a[10];
    printf(\"%d\",(int)sizeof(a)); //prints 10*sizeof(int) (40 on         


        
4条回答
  •  耶瑟儿~
    2021-01-04 09:30

    sizeof() returns the size of a type, so the type is what's important.

    It also shouldn't be printed with %d. At the very least, explicitly cast it to unsigned long or unsigned long long and use the appropriate format specifier. When teaching C, I had a student get the wrong answer by printing size_t with %d as the textbook mistakenly said to do.

    Anyway, a is an array type. In C, array types decay to pointer types if you do almost anything with them or sneeze loudly, so almost anything you do to a will yield a pointer type. As you've found out, adding or subtracting a number will decay. (After all, an array can't be used in arithmetic, but a pointer can.)

提交回复
热议问题