harsh
harsh

Reputation: 109

How to calculate size of array from pointer variable?

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.

Upvotes: 2

Views: 3911

Answers (3)

paxdiablo
paxdiablo

Reputation: 881113

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.

Upvotes: 5

Roee Gavirel
Roee Gavirel

Reputation: 19445

No. arrays in C doesn't have this info. you should hold a variable "next" to the array with this data.

if you have the array it self you can use the sizeof to get his size in compilation stage.

char array1[XXX];
char* pointer1 = array1;
sizeof(array1); // this is XXX
sizeof(pointer1); // this is the size of a pointer in your system

you should do the following and use the variable in you program (or pass it to function when you passing the array to a function)

int array1size = sizeof(array1);

Upvotes: 0

Dietrich Epp
Dietrich Epp

Reputation: 213258

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

Upvotes: 11

Related Questions