3

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

Thanks in advance.

Taryn East
  • 27,486
  • 9
  • 86
  • 108

4 Answers4

11

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
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • +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 Jun 21 '10 at 20:56
3

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

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
0

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
  • 1,370
  • 2
  • 13
  • 24
0

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

AndiDog
  • 68,631
  • 21
  • 159
  • 205