Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate memory dynamically for a char array in C++?

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
  1. Why does the pointer 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?
  2. Why does dereferencing give only the first character in the array?
  3. How can I get the memory address then, in this case?
like image 655
HJS Avatar asked May 27 '15 12:05

HJS


2 Answers

The operator<< of output streams has an overload to char* that interprets the character array as a string instead of a generic pointer. Thus, it prints the value of the string. Use static_cast<void*>(pvalue2) to print the address.

Dereferencing the string gives you a char, which is not a string.

If you are using C++, prefer using std::string instead of character arrays. If you need a C-style string for something, you can get a character array representation of the string by calling the c_str() method.

like image 148
petersohn Avatar answered Oct 01 '22 07:10

petersohn


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);
like image 34
Mike Seymour Avatar answered Oct 01 '22 07:10

Mike Seymour