how to get size of char array in c++
To get the size of a char array in C++, you can use the sizeof
operator. Here are the steps to do so:
Declare and initialize the char array:
cpp char myArray[] = "Hello";
Use the
sizeof
operator to get the size of the array:cpp int size = sizeof(myArray);
Explanation: The sizeof
operator returns the size of an object or type in bytes. In this case, we pass the myArray
variable to sizeof
to get the size of the array. The result is the total number of bytes occupied by the array.
- Print the size:
cpp std::cout << "Size of array: " << size << std::endl;
Explanation: The std::cout
object is used to print the size of the array to the console. The <<
operator is used to concatenate the message "Size of array: " with the value of the size
variable. The std::endl
is used to insert a newline character and flush the output buffer.
So, the complete code would look like this:
#include <iostream>
int main() {
char myArray[] = "Hello";
int size = sizeof(myArray);
std::cout << "Size of array: " << size << std::endl;
return 0;
}
When you run this code, it will output:
Size of array: 6
The output is 6 because the sizeof
operator includes the null character \0
at the end of the string literal "Hello".