Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate size of array from pointer variable?

Tags:

arrays

c

pointers

i have pointer of array(array which is in memory). Can i calculate the size of array from its pointer ? i dont know actually where is the array in memory. i only getting pointer adress(suppose 9001) using that adress i have to calculate array size.

Thanks.

like image 417
harsh Avatar asked May 12 '26 19:05

harsh


2 Answers

No, you cannot calculate the size of the array. Objects in C do not carry type information, so you must arrange to know the size of the array ahead of time. Something like this:

void my_function(int array[], int size);
like image 50
Dietrich Epp Avatar answered May 14 '26 10:05

Dietrich Epp


You cannot do this in C. The size of a pointer is the size of a pointer, not the size of any array it may be pointing at.

If you end up with a pointer pointing to an array (either explicitly with something like char *pch = "hello"; or implicitly with array decay such as passing an array to a function), you'll need to hold the size information separately, with something like:

int twisty[] = [3,1,3,1,5,9];
doSomethingWith (twisty, sizeof(twisty)/sizeof(*twisty));
:
void doSomethingWith (int *passages, size_t sz) { ... }

The following code illustrates this:

#include <stdio.h>

static void fn (char plugh[], size_t sz) {
    printf ("sizeof(plugh) = %d, sz = %d\n", sizeof(plugh), sz);
}

int main (void) {
    char xyzzy[] = "Pax is a serious bloke!";
    printf ("sizeof(xyzzy) = %d\n", sizeof(xyzzy));
    fn (xyzzy, sizeof(xyzzy)/sizeof(*xyzzy));
    return 0;
}

The output on my system is:

sizeof(xyzzy) = 24
sizeof(plugh) = 4, sz = 24

because the 24-byte array is decayed to a 4-byte pointer in the function call.

like image 43
paxdiablo Avatar answered May 14 '26 10:05

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!