我试图在其初始化的不同函数中获取sizeof char数组变量但是无法获得正确的sizeof.请看下面的代码
int foo(uint8 *buffer){
cout <<"sizeof: "<< sizeof(buffer) <<endl;
}
int main()
{
uint8 txbuffer[13]={0};
uint8 uibuffer[4] = "abc";
uint8 rxbuffer[4] = "def";
uint8 l[2]="g";
int index = 1;
foo(txbuffer);
cout <<"sizeof after foo(): " <<sizeof(txbuffer) <<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
sizeof: 4
sizeof after foo(): 13
Run Code Online (Sandbox Code Playgroud)
期望的输出是:
sizeof: 13
sizeof after foo(): 13
Run Code Online (Sandbox Code Playgroud)
Mar*_*lon 15
仅使用指针无法完成此操作.指针不包含有关数组大小的信息 - 它们只是一个内存地址.因为数组在传递给函数时会衰减为指针,所以会丢失数组的大小.
然而,一种方法是使用模板:
template <typename T, size_t N>
size_t foo(const T (&buffer)[N])
{
cout << "size: " << N << endl;
return N;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样调用函数(就像任何其他函数一样):
int main()
{
char a[42];
int b[100];
short c[77];
foo(a);
foo(b);
foo(c);
}
Run Code Online (Sandbox Code Playgroud)
输出:
size: 42
size: 100
size: 77
Run Code Online (Sandbox Code Playgroud)