ra170 ra170 - 2 months ago 18
C++ Question

initializing char and char pointers

What's the difference between these:

This one works:

char* pEmpty = new char;
*pEmpty = 'x';


However if I try doing:

char* pEmpty = NULL;
*pEmpty = 'x'; // <---- doesn't work!


and:

char* pEmpty = "x"; // putting in double quotes works! why??


EDIT: Thank you for all the comments:
I corrected it. it was supposed to be pEmpty ='x',
So, this line doesn't even compile: char
pEmpty ='x';
wheras this line works: char* pEmpty ="x"; //double quotes.

Answer

The difference is that string literals are stored in a memory location that may be accessed by the program at runtime, while character literals are just values. C++ is designed so that character literals, such as the one you have in the example, may be inlined as part of the machine code and never really stored in a memory location at all.

To do what you seem to be trying to do, you must define a static variable of type char that is initialized to 'x', then set pEmpty to refer to that variable.