2018-01-14 创建人:Ruo_Xiao
开发环境:VS2010
1、‘a’:代表字符,用8个b存储该字符的ASCII码值,即97。
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char c1 = 'a';
char c2 = 97;
char c3 = -97;
char c4 = 129;
char *p1 = &c1;
char *p2 = &c2;
char *p3 = &c3;
cout<<"sizeof(c1) = "<<sizeof(c1)<<endl;
cout<<c1<<endl;
cout<<c2<<endl;
cout<<c3<<endl;
cout<<c4<<endl;
cin.get();
return 0;
}
由上述代码可知:
(1)给char型变量赋值时,‘a’和其ASCII码值97的结果是一样的,都被翻译成了‘a’。
(2)存储于8个b的内存块。
(3)由于ASCII码值是从1~128的,故给char型赋128以上的数或者小于1的数,程序无法显示。
(4)经过调试,得到:
p1的值为0x002aff23;
p2的值为0x002aff17;
在内存表中,这两个值如下:
上图中“61”是十六进制,转化为十进制为97,故char型值在内存中存储的是其ASCII码值。
2、“a”代表字符串,编译器会自动翻译成“const char[2]”,其末尾会自动加上’\0’,故其代表了字符数组!
3、‘abc’:按理报错,但是vs2010做了一些处理,实验结果如下:
(1)只取最后一个字符。
char c = 'a1b0';
cout<<c<<endl;
cin.get();
(2)字符数量有限制,只能是小于5个,大于等于5都报错。
char c = 'a1b01'; //error,常量中字符太多
cout<<c<<endl;
cin.get();
4、“abc”同理于“a”。