find sizeof char array C++

纵饮孤独 提交于 2019-12-03 15:36:17

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

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:

template<typename T, size_t size>
size_t getSize(T (& const)[ size ])
{
    std::cout << "Size: " << size << "\n";
    return size;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!