I have a char array declared as char input[], and I want to know how to find its size or length. What is the correct syntax or method in C++ to determine the length or size of the char array?
Could you please provide code examples
Nilesh Kudale is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
8
Where the name of an array is in scope, you can use sizeof
to find the size of that array.
char foo[1234];
std::cout << sizeof(foo); // should print 1234
There is, however, a twist to this: when/if you attempt to define a function parameter with a type array of T
, the parameter will actually have the type pointer to T
. So, if you have something like this:
void printSize(char param[]) {
std::cout << sizeof(param) << "n";
}
int main() {
char foo[1234];
char bar[2345];
printSize(foo);
printSize(bar);
}
On a reasonably current compiler, this will generally print out 8
for both sizes. On an older compiler, you might get 4 for both. If you get a really old (MS-DOS) compiler, you could even get 2 for both. But always the same size for both, and virtually always 2, 4, or 8.
It’s also possible to pass the array to a function template by reference, in which case you can maintain the information about the array’s size:
template <std::size_t N>
void printSize(char (&array)[N]) {
std::cout << N << "n";
}
int main() {
char foo[1234];
char bar[2345];
printSize(foo);
printSize(bar);
}
This should print the sizes as 1234
and 2345
. And since printSize
is defined to receive an array by reference, if you try to pass something like a pointer instead of an array, the code simply won’t compile.
Since it’s a template anyway, it’s easy to make this work for arrays of different types, not just arrays of char
:
template <typename T, std::size_t N>
void printSize(T (&array)[N]) {
std::cout << N << "n";
}
int main() {
char foo[1234];
long bar[2345];
printSize(foo);
printSize(bar);
}
This can produce different results from the first code above though. sizeof
yields the number of bytes in an array, but this prints out the number of elements in the array. For any type that isn’t one byte, the results will be different (e.g., an array of 1000 short
s will have 1000 elements, but since short
is usually two bytes, the sizeof
version will show its size as 2000
instead).
Though it’s one most would generally advise avoiding, there’s one other possibility I suppose I need to mention. You can define a global variable in one file, and a declare it in another. The definition needs to specify the size, but the declaration does not. If the declaration doesn’t specify the size, that variable has an incomplete type in the file where it’s declared, so even though you can use it in some ways, you can’t take its size (in that file). To allow sizeof
to work on it, you have to specify its size in the declaration.
extern char foo[]; // legal, but incomplete type
extern char bar[1234]; // legal, complete type
1