Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing char and char pointers

Tags:

c++

char

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.

like image 621
ra170 Avatar asked Dec 13 '22 22:12

ra170


1 Answers

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.
like image 67
danben Avatar answered Dec 15 '22 14:12

danben