views:

169

answers:

4

Hi, I have a pointer (uint8_t *myPointer), that I pass as paramether to a method, and then this method set the value to this pointer, but I want to know how much bytes are used (pointed ?) by the myPointer variable.

Thanks in advance and excuse me by my english.

+3  A: 

You can't. You must pass the size of the buffer pointed to by the pointer yourself.

Billy ONeal
A: 

You can't. Unless the array is instantiated at compile time. Example int test[] = {1, 2, 3, 4}; In that case, you can use sizeof(test) to return you the correct size. Otherwise, it's impossible to tell the size of an array without storing a counter of your own.

Stefan Valianu
+10  A: 

The size of the pointer: sizeof(myPointer) (Equal to sizeof(uint8_t*))
The size of the pointee: sizeof(*myPointer) (Equal to sizeof(uint8_t))

If you meant that this points to an array, there is no way to know that. A pointer just points, and cares not where the value is from.

To pass an array via a pointer, you'll need to also pass the size:

void foo(uint8_t* pStart, size_t pCount);

uint8_t arr[10] = { /* ... */ };
foo(arr, 10);

You can use a template to make passing an entire array easier:

template <size_t N>
void foo(uint8_t (&pArray)[N])
{
    foo(pArray, N); // call other foo, fill in size.
    // could also just write your function in there, using N as the size
}

uint8_t arr[10] = { /* ... */ };
foo(arr); // N is deduced
GMan
+1 -- but it should be noted that if `foo` is a big function you'll incur code bloat with the template if the number of different values of N is large. You can mitigate this by making foo a stub which calls an overload of foo accepting an explicit length parameter.
Billy ONeal
A: 

I assume you mean the memory needed for the pointer only. You can check this at compile time with sizeof(myPointer).

AndiDog