Find size of array without using sizeof

前端 未结 6 1803
陌清茗
陌清茗 2020-12-03 03:48

I was searching for a way to find the size of an array in C without using sizeof and I found the following code:

int main ()
{
    int arr[100];         


        
6条回答
  •  半阙折子戏
    2020-12-03 03:55

    &arr gives you a pointer to the array. (&arr)[1] is equivalent to *(&arr + 1). &arr + 1 gives you a pointer to the array of 100 ints that follows arr. Dereferencing it with * gives you that array that follows. Since this array is used in an additive expression (-), it decays to the pointer to its first element. The same happens to arr in the expression. So you subtract to pointers, one pointing to the non-existent element right after arr and the other pointing to the first element of arr. This gives you 100.

    But it's not working. %d is used for int. Pointer difference returns you ptrdiff_t and not int. You need to use %td for ptrdiff_t. If you lie to printf() about the types of the parameters you're passing to it, you get well-deserved undefined behavior.

    EDIT: (&arr)[1] may cause undefined behavior. It's not entirely clear. See the comments below, if interested.

提交回复
热议问题