查找 char 数组的大小 C++
我试图在初始化的不同函数中获取 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;
}
输出是:
sizeof: 4
sizeof after foo(): 13
期望的输出是:
sizeof: 13
sizeof after foo(): 13
im trying to get the sizeof char array variable in a different function where it was initialize however cant get the right sizeof. please see code below
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;
}
the output is:
sizeof: 4
sizeof after foo(): 13
desired output is:
sizeof: 13
sizeof after foo(): 13
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅靠指针无法完成此操作。指针不包含有关数组大小的信息 - 它们只是一个内存地址。由于数组在传递给函数时会衰减为指针,因此会丢失数组的大小。
然而,一种方法是使用模板:
然后您可以像这样调用该函数(就像任何其他函数一样):
输出:
This can't be done with pointers alone. Pointers contain no information about the size of the array - they are only a memory address. Because arrays decay to pointers when passed to a function, you lose the size of the array.
One way however is to use templates:
You can then call the function like this (just like any other function):
Output:
你不能。在 foo 中,您要求“uint8_t 指针”的大小。如果您需要在 foo 中将大小作为单独的参数传递。
You cant. In foo you are asking for the size of a "uint8_t pointer". Pass the size as a separate parameter if you need it in foo.
一些模板魔法:
Some template magic: