Search code examples
arrayscpointersimplicit-conversionfunction-declaration

size of array in C without sizeof and not in main function


I want to understand how to know the size of array without using sizeof and not in main function. and i really want to understand why my code not working when i do it in other function.(in main it works same as sizeof). >>> The rasult i got are some trash numbers

*with char array is understood but i dont know how to do it with other data specifiers.

#include <stdio.h>

void arrSize(int a[],int b[]){
    int size_a = *(&a+1) - a;
    int size_b = *(&b+1) - b;
    printf("%d,%d",size_a,size_b);
}

int main(){
    int arr[] = {2,12,14,16};
    int brr[] = {8,53,2,4,16};
    
    arrSize(arr,brr);

    return 0;
}

Solution

  • This function declaration

    void arrSize(int a[],int b[]){
        int size_a = *(&a+1) - a;
        int size_b = *(&b+1) - b;
        printf("%d,%d",size_a,size_b);
    }
    

    is adjusted by the compiler to the following declaration

    void arrSize(int *a,int *b){
        int size_a = *(&a+1) - a;
        int size_b = *(&b+1) - b;
        printf("%d,%d",size_a,size_b);
    }
    

    That is parameters having array types are adjusted by the compiler to pointers to array element types.

    On the other hand, in this call

    arrSize(arr,brr);
    

    the arrays are implicitly converted to pointers to their first elements.

    Having a pointer to the first element of an array you are unable to determine the array size pointed to by the pointer.

    the initializers in these declarations

        int size_a = *(&a+1) - a;
        int size_b = *(&b+1) - b;
    

    invoke undefined behavior because you are dereferencing pointers that do not point to valid object.