1 单引号和双引号
C语言中的单引号用来表示字符字面量。
‘a’表示字符字面量。
在内存中占1个字节。
‘a’+ 1表示‘a’的ASCII码加1,结果为‘b’。
C语言中的双引号用来表示字符串字面量。
“a”表示字符串字面量。
在内存中占2个字节。
“a”+ 1表示指针运算,结果指向“a”结束符‘\0’。
下面的程序片段合法么?
char* p1 = 1 ;
char* p2 = ‘1’;
char* p3 = “1”;
#include <stdio.h>
int main()
{
char* p1 = 1 ;
//warning: initialization makes pointer from integer without a cast
char* p2 = '1';
//warning: initialization makes pointer from integer without a cast
char* p3 = "1";
printf("%s, %s, %s", p1, p2, p3);
//Segmentation fault (core dumped)
printf('\n');
//warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast
//note: expected ‘const char * __restrict__’ but argument is of type ‘int’
//extern int printf (const char *__restrict __format, ...);
// warning: format not a string literal and no format arguments
//Segmentation fault (core dumped)
printf("\n");
return 0;
}
//note也是警告信息的一种
2 小贴士
字符字面量被编译为对应的ASCII码。
字符串字面量被编译为对应的内存地址。
printf的第一个参数被当成字符串内存地址。
内存的低地址空间不能在程序中随意访问。
程序实例分析1
程序实例分析2
实例分析:混淆概念的代码
#include <stdio.h>
int main()
{
char c = " ";
//warning: initialization makes integer from pointer without a cast
while( (c == "\t") || (c == " ") || (c == "\n") )
// warning: comparison between pointer and integer
{
scanf("%c", &c);
}
return 0;
}
程序实例分析
char c = “string”;发生了什么?
分析:
编译后字符串“string”的内存地址被赋值给变量c。
内存地址占用4个字节,而变量c只占用1个字节。
由于类型不同,赋值后产生截断。
3 小结
单引号括起来的单个字符代表整数。
双引号括起来的字符代表字符指针。
C编译器接受字符和字符串的比较,无任何意义。
C编译器允许字符串对字符变量赋值,只能得到错误
参考:https://blog.csdn.net/qq_20233867/article/details/78472161