gpt4 book ai didi

c++ - 查找 sizeof char 数组 C++

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:37 24 4
gpt4 key购买 nike

我试图在另一个初始化它的函数中获取 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

最佳答案

单靠指针是做不到的。指针不包含有关数组大小的信息——它们只是一个内存地址。因为数组在传递给函数时会衰减为指针,所以您会损失数组的大小。

然而,一种方法是使用模板:

template <typename T, size_t N>
size_t foo(const T (&buffer)[N])
{
cout << "size: " << N << endl;
return N;
}

然后您可以像这样调用该函数(就像任何其他函数一样):

int main()
{
char a[42];
int b[100];
short c[77];

foo(a);
foo(b);
foo(c);
}

输出:

size: 42
size: 100
size: 77

关于c++ - 查找 sizeof char 数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8273553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com