char *a = new char[10];
My question is that how can I get the length of a char *
It is very simply.:) It is enough to add only one statement
size_t N = 10;
char *a = new char[N];
Now you can get the size of the allocated array
std::cout << "The size is " << N << std::endl;
Many mentioned here C standard function std::strlen. But it does not return the actual size of a character array. It returns only the size of stored string literal.
The difference is the following. if to take your code snippet as an example
char a[] = "aaaaa";
int length = sizeof(a)/sizeof(char); // length=6
then std::strlen( a ) will return 5 instead of 6 as in your code.
So the conclusion is simple: if you need to dynamically allocate a character array consider usage of class std::string
. It has methof size and its synonym length that allows to get the size of the array at any time.
For example
std::string s( "aaaaa" );
std::cout << s.length() << std::endl;
or
std::string s;
s.resize( 10 );
std::cout << s.length() << std::endl;