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.
Your second line doesn't work because you are trying to assign 'x'
to pEmpty
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.
char *p = new char(); // Now I have a variable named p that contains
// the memory address of a single piece of character
// data.
*p = 'x'; // Here I assign the letter 'x' to the dereferenced value of p;
// that is, I look up the location of the memory address contained
// in p and put 'x' there.
p = 'x'; // This is illegal because p contains a memory address,
// not a character.
char q = 'x'; // Now I have a char variable named q containing the
// character 'x'.
p = &q; // Now I assign the address of q (obtained with the reference
// operator &) to p. This is legal because p contains a memory
// address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With