如何找到指针使用的字节数?

Nob*_*ody 3 c c++ pointers objective-c

我有一个指针(uint8_t*myPointer),我作为参数传递给一个方法,然后这个方法为这个指针设置一个值,但我想知道myPointer变量使用了多少字节(指向?).

提前致谢.

GMa*_*ckG 11

指针的大小:( sizeof(myPointer)等于sizeof(uint8_t*))
指针的大小:( sizeof(*myPointer)等于sizeof(uint8_t))

如果你的意思是这指向一个数组,那么就没有办法知道这一点.指针只是指向,而不关心值的来源.

要通过指针传递数组,您还需要传递大小:

void foo(uint8_t* pStart, size_t pCount);

uint8_t arr[10] = { /* ... */ };
foo(arr, 10);
Run Code Online (Sandbox Code Playgroud)

您可以使用模板更轻松地传递整个数组:

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
Run Code Online (Sandbox Code Playgroud)