For a char []
, I can easily get its length by:
char a[] = "aaaaa";
int length = sizeof(a)/sizeof(char); // length=6
However, I cannot do like this to get the length of a char *
by:
char *a = new char[10];
int length = sizeof(a)/sizeof(char);
because, I know, a
here is a pointer, such that length
here will be always be 4
(or something other in different systems).
My question is that how can I get the length of a char *
afterwards? I know someone may challenge me that you already know its 10
because you just created it. I want to know this because this step of getting its length may come long long way from its creation and I don't want to come long long way back to check this number. Moreover, I also want to know its real length.
To be more specific
- how can I get its real
length=5
? - how can I get its total
length=10
?
for the following example:
char *a = new char[10];
strcpy(a, "hello");
Just use
std::vector<char>
which keep the (dynamic) size for you. (Bonus, memory management for free).Or
std::array<char, 10>
which keep the (static) size.Create a structure to keep the info, something like:
You can make a back-tracker character, ex, you could append any special character say "%" to the end of your string and then check the occurrence of that character.
But this is a very risky way as that character can be in other places also in the char*
Otherwise define a custom structure to keep track of length and allocate memory.
It is very simply.:) It is enough to add only one statement
Now you can get the size of the allocated array
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
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
or
You can find the length of a char* string like this:
sprintf() prints mystring onto itself, and returns the number of characters printed.
You could try this:
If the
char *
is 0-terminated, you can usestrlen
Otherwise, there is no way to determine that information