I am learning about dynamic memory in C++. What I learned as a standard way of allocating & deallocating dynamically for any data type is, for example,
//For double,
double* pvalue1 = nullptr;
pvalue1 = new double;
*pvalue1 = 17.3;
delete pvalue1; //free up when I'm done
BUT, for a char
array, I learned that it's handled differently:
char* pvalue2 = nullptr;
pvalue2 = new char[6];
strncpy(pvalue2,"Hello",sizeof("Hello"));
std::cout << "Pointed-to value of pvalue2 is " << *pvalue2 << std::endl;
std::cout << "Value of pvalue2 is " << pvalue2 << std::endl;
delete [] pvalue2; //free up when I'm done
Then, on command prompt:
Pointed-to value of pvalue2 is H
Value of pvalue2 is Hello
pvalue2
give the "pointed-to" string literal
instead of the memory address? Isn't a "pointer value" always the memory address which it points to?Why does the pointer pvalue2 give the "pointed-to" string literal instead of the memory address?
Because there's a special overload of <<
so that streaming char*
will give the string it points to, not the pointer value. That's usually what you want to happen.
Isn't a "pointer value" always the memory address which it points to?
Yes.
Why does dereferencing give only the first character in the array?
Because a pointer contains the address of a single object, which in this case is the first element of the array. Other elements can be accessed using pointer arithmetic, e.g. pvalue2[2]
for the third element.
How can I get the memory address then, in this case?
To print it with <<
, convert to a different pointer type to avoid the char*
overload:
std::cout << static_cast<void*>(pvalue2);