When you have an array, you can use sizeof
to get the total memory used by the array.
char buffer[20];
//
// ...
//
size_t size = sizeof(buffer); // This gives you total memory needed to hold buffer.
size_t length = sizeof(buffer)/sizeof(char); // In this case size and length will be
// same since sizeof(char) is 1.
If you have an array of other types,
int buffer[20];
//
// ...
//
size_t size = sizeof(buffer); // This gives you total memory needed to hold buffer.
size_t length = sizeof(buffer)/sizeof(int); // The length of the array.
There are pitfalls to be aware of using sizeof
to get the memory used by an array. If you pass buffer
to a function, you lose the ability to compute the length of the array.
void foo(char* buffer)
{
size_t size = sizeof(buffer); // This gives you the size of the pointer
// not the size of the array.
}
void bar()
{
char buffer[20];
// sizeof(buffer) is 20 here. But not in foo.
foo(buffer);
}
If you need to be able to compute the length of the array at all times, std::vector<char>
and std::string
are better choices.
void foo(std::vector<char>& buffer)
{
size_t size = buffer.size() // size is 20 after call from bar.
}
void bar()
{
std::vector<char> buffer(20);
size_t size = buffer.size() // size is 20.
foo(buffer);
}