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.
The second example doesn't work for a few reasons. The first one would be that you have made the pointer point to, well, nowhere in particular. The second is that you didn't actually dereference it, so you are telling the pointer to point to the address of a character literal. As it has no address, the compiler will complain.
EDIT:
Just to be clear, the asterisk (*) is the operator that dereferences pointers.
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 setpEmpty
to refer to that variable.Your second line doesn't work because you are trying to assign
'x'
topEmpty
rather than*pEmpty
.Edit: Thanks to Chuck for the correction. It ALSO doesn't work because you need to allocate some memory to hold the value
'x'
. See the example below.The third line does work because you are using an initalizer rather than a regular assignment statement.
In general, you should understand how pointers and dereferencing work.
pEmpty = 'x';
assignspEmpty
(rather than the memory pointed by it) the value of 'x'.You need to keep in mind what a pointer is — it's just a normal variable that holds an address, much like a
char
holds a character value. This address can be used to look up another variable (with the*
operator).When you do
char* pEmpty = new char
, you're givingpEmpty
the value returned bynew char
, which is the address of a chunk of memory large enough to hold a char value. Then you use*pEmpty
to access this memory and assign it the char value'x'
.In the second example, you write
pEmpty = 'x'
— but remember thatpEmpty
is a pointer, which means it's supposed to hold an address. Is'x'
an address? No, it's a character literal! So that line isn't really meaningful.In the third example, you're assigning
pEmpty
the string literal"x"
. Is this an address? Yes, it is. The literal evaluates to the address of that constant string.Remember, pointers are a completely different thing from the type that they point to. They can be used to access a value of that type, but they are a completely different type of their own.