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
- Why does the pointer
pvalue2give 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 dereferencing give only the first character in the array?
- How can I get the memory address then, in this case?