查找sizeof char数组C ++ [英] find sizeof char array C++

查看:233
本文介绍了查找sizeof char数组C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获得sizeof字符数组变量在不同的函数,它是初始化,但无法得到正确的sizeof。请参阅下面的代码

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;
}

输出为:

sizeof: 4
sizeof after foo(): 13

所需的输出是:

sizeof: 13
sizeof after foo(): 13


推荐答案

这不能单独使用指针。指针不包含有关数组大小的信息 - 它们只是一个内存地址。因为数组传递到函数时会衰减到指针,所以会丢失数组的大小。

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.

一种方法是使用模板:

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);
}

输出:

size: 42
size: 100
size: 77

这篇关于查找sizeof char数组C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆