Is std::size and sizeof same for a char array?

70 views Asked by At

If I use std::size and sizeof() for a char array, it gives the same value, so are those same for char array? I think these 2 work differently for different types, but are they same for char?

2

There are 2 answers

4
Martin Cook On

.size() returns the number of elements, whereas sizeof() returns the number of bytes. For a character array, each element is one byte, which explains why the number is the same

3
Christian Stieber On

It's kindof sortof the case in thios particular example, but you shouldn't care. Observe:

#include <iostream>

int main(void)
{
    {
        char test[3];
        std::cout << "std::size(char[]): " << std::size(test) << '\n';
        std::cout << "sizeof(char[]): " << sizeof(test) << '\n';
    }

    std::cout << '\n';

    {
        int test[3];
        std::cout << "std::size(int[]): " << std::size(test) << '\n';
        std::cout << "sizeof(int[]): " << sizeof(test) << '\n';
    }

    return 0;
}
stieber@gatekeeper:~ $ g++ -std=c++20 Test.cpp && ./a.out
std::size(char[]): 3
sizeof(char[]): 3

std::size(int[]): 3
sizeof(int[]): 12

sizeof() simply gives you the storage size of an object; this is something you'd need to allocate memory via malloc, for example.

std::size() gives you the number of items inside -- which is a very different thing, and more likely what you want. Although using C-style arrays comes with its own pitfalls anyway -- so that's also something you might not want to do.