char* string = "hello there";
cout << sizeof( string ); // prints 4, which is the size of pointer
cout << sizeof( *string ); // prints 1, which is the size of char
How do I get the number of characters contained in the string (11)?
char* string = "hello there";
cout << sizeof( string ); // prints 4, which is the size of pointer
cout << sizeof( *string ); // prints 1, which is the size of char
How do I get the number of characters contained in the string (11)?
It's strlen
you want for that, not sizeof
. The first counts the number of characters up to the terminating NUL while the second gives you the size of the type which, in this case, is a pointer rather than the underlying array of characters.
By that last point, I mean:
char *x = "hello there";
char y[] = "hello there";
std::cout << sizeof(x) << ' ' << sizeof(y) << '\n';
will most likely output something like:
4 12
on a system with 32-bit pointers (and 8-bit char
). In that case, the 4
is the size of the pointer, the 12
is the number of bytes in the array (including the NUL at the end).
In any case, that's moot, since strlen()
is the right way to get the length of a C string (yes, even in C++, though you may want to consider using the C++ strings since they may save you a lot of trouble).
The function sizeof()
returns the size of a data type in Byte
For example because you define:
char* string = "hello there";
then type of string
is char *
and size of mostly all pointer is 4 Bytes ( this function returns 4) But type of *string
is char
and size of every character is 1 Byte ( This function returns 1)
Solution for you :
Alternative 1:
Use function strlen()
in library 'string.h'
Alternative 2:(from scratch)
int length = 0;
int index = 0;
while ( string[index] != '\0')
{
length++;
index++;
}