C语言容易迷茫的地方,这哥仨一起组合出来,绝对容易蒙,现在遇到了总结出来,以后遇到再补充进来。
- sizeof与strlen
#include<stdio.h>
int main()
{
char a[] = "hello";
char *p = a;
printf("%d\n",sizeof(a));
printf("%d\n",sizeof(p));
printf("%d\n",strlen(a));
printf("%d\n",strlen(p));
}
6
4
5
5
Press any key to continue
strlen()是函数,遇到 ’ \0 ‘ 停止,并且返回长度。所以传入一个地址即可,a与p都是字符串首地址。
- 关于字符串常量:
#include<stdio.h>
int main()
{
char a[] = "hello";
char *p = "world"; // 注意p指向常量字符串
a[0] = 'X';
printf("%s\n",a);
p[0] = 'X'; // 试图修改常量,但是!!!编译器不能发现该错误,到运行才崩溃。我之前以为会报不能给常量赋值的错误。
printf("%s\n",p);
}