There is some apparent confusion that needs to be cleared first.
// like char point
//char *charptr="Hello";
// its length is 5 |
"Hello" is an array of six const char (it holds the characters 'H', 'e', 'l', 'l', 'o', and '\0';). To see that, print its sizeof:
std::cout << sizeof "Hello" << '\n';
charptr is a pointer. Like any pointer, its size is the same regardless of what it points to, it is the size necessary to store an address on your platform, typically 4 or 8 bytes, You can see that if you print its sizeof:
std::cout << sizeof charptr << '\n';
The line
char *charptr="Hello";
is an error in C++ (it used to be supported for C compatibility), it's properly written as
const char *charptr="Hello";
. This line puts into charptr the address of the character 'H' from your string.
The only way to get the number 5 that you saw is to examine the memory locations after 'H' until you find '\0' and count the number of characters seen. The C library function strlen() does that:
std::cout << strlen(charptr) << '\n';
Finally, the line
int *intptr={1,2,5};
is an error. You can do
int *intptr= new int[3]{1,2,5};
in modern C++, but there is no way to get that 3 from the resulting pointer. Use
vector<int>
if you're looking for dynamically allocated arrays in C++, then you can obtain the number of elements by calling the member function
.size()