这些有什么区别:
这个有效:
char* pEmpty = new char;
*pEmpty = 'x';
但是,如果我尝试这样做:
char* pEmpty = NULL;
*pEmpty = 'x'; // <---- doesn't work!
and:
char* pEmpty = "x"; // putting in double quotes works! why??
编辑:感谢您的所有评论:
我纠正了。本来应该是pEmpty='x',
所以,这一行甚至无法编译: charpEmpty = 'x';而这一行有效: char* Empty ="x"; //双引号。
您的第二行不起作用,因为您正在尝试分配'x'
to pEmpty
而不是*pEmpty
.
Edit: 感谢 Chuck 的指正。它也不起作用,因为您需要分配一些内存来保存该值'x'
。请参阅下面的示例。
第三行确实有效,因为您使用的是初始值设定项而不是常规赋值语句。
一般来说,您应该了解指针和取消引用的工作原理。
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)