初始化char和char指针

ra1*_*170 4 c++ char

这些之间有什么区别:

这个工作:

char* pEmpty = new char;
*pEmpty = 'x';
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试做:

char* pEmpty = NULL;
*pEmpty = 'x'; // <---- doesn't work!
Run Code Online (Sandbox Code Playgroud)

和:

char* pEmpty = "x"; // putting in double quotes works! why??
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢你的所有意见:我纠正了它.它应该是pEmpty ='x',所以,这行甚至不编译:char pEmpty ='x'; 这行有效:char*pEmpty ="x"; //双引号.

dan*_*ben 10

因为你试图分配你的第二个行不起作用'x'pEmpty,而不是*pEmpty.

编辑:感谢Chuck的纠正.它也不起作用,因为你需要分配一些内存来保存值'x'.请参阅下面的示例.

第三行确实有效,因为您使用的是initalizer而不是常规赋值语句.

通常,您应该了解指针和解除引用的工作原理.

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.
Run Code Online (Sandbox Code Playgroud)


Jef*_*dge 1

区别在于字符串文字存储在程序在运行时可以访问的内存位置,而字符文字只是值。C++ 的设计使得字符文字(例如示例中的字符文字)可以作为机器代码的一部分内联,并且根本不会真正存储在内存位置中。

要执行您似乎想要执行的操作,您必须定义一个char初始化为 类型的静态变量'x',然后设置pEmpty为引用该变量。