In C, are arrays pointers or used as pointers?

前端 未结 6 916
野趣味
野趣味 2020-11-22 05:23

My understanding was that arrays were simply constant pointers to a sequence of values, and when you declared an array in C, you were declaring a pointer and allocating spac

6条回答
  •  别那么骄傲
    2020-11-22 05:37

    sizeof is evaluated at compile-time, and the compiler knows whether the operand is an array or a pointer. For arrays it gives the number of bytes occupied by the array. Your array is a char[] (and sizeof(char) is 1), thus sizeof happens to give you the number of elements. To get the number of elements in the general case, a common idiom is (here for int):

    int y[20];
    printf("number of elements in y is %lu\n", sizeof(y) / sizeof(int));
    

    For pointers sizeof gives the number of bytes occupied by the raw pointer type.

提交回复
热议问题