初始化char和char指针 [英] initializing char and char pointers

查看:121
本文介绍了初始化char和char指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些之间有什么区别:

此功能有效:

char* pEmpty = new char;
*pEmpty = 'x';

但是,如果我尝试这样做:

However if I try doing:

char* pEmpty = NULL;
*pEmpty = 'x'; // <---- doesn't work!

和:

char* pEmpty = "x"; // putting in double quotes works! why??

编辑:感谢您的所有评论:
我更正了它。应该是 pEmpty ='x',
所以,这一行甚至都没有编译:char
pEmpty ='x';
wheras这行有效:char * pEmpty = x; //双引号。

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.

推荐答案

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

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.

要做您想做的事情,必须定义一个类型为 char 的静态变量,并将其初始化为'x',然后设置 pEmpty 来引用该变量。

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 set pEmpty to refer to that variable.

这篇关于初始化char和char指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆