Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading