查找 char 数组的大小 C++

发布于 2024-12-17 19:37:50 字数 552 浏览 3 评论 0原文

我试图在初始化的不同函数中获取 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

嘿嘿嘿 2024-12-24 19:37:50

仅靠指针无法完成此操作。指针不包含有关数组大小的信息 - 它们只是一个内存地址。由于数组在传递给函数时会衰减为指针,因此会丢失数组的大小。

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

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

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:

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

You can then call the function like this (just like any other function):

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

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

Output:

size: 42
size: 100
size: 77
沉默的熊 2024-12-24 19:37:50

你不能。在 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.

你的他你的她 2024-12-24 19:37:50

一些模板魔法:

template<typename T, size_t size>
size_t getSize(T (& const)[ size ])
{
    std::cout << "Size: " << size << "\n";
    return size;
}

Some template magic:

template<typename T, size_t size>
size_t getSize(T (& const)[ size ])
{
    std::cout << "Size: " << size << "\n";
    return size;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文