字符串常量
char* s = "Hello,world!";
#include<stdio.h>
int main(void){
int i=0;
char* s = "Hello World";
char* s2 = "Hello World";
//s[0]='B';//erro:不能写,只能读
printf("&i=%p\n",&i);
printf("s =%p\n",s);
printf("s2=%p\n",s2);
printf("here!s[0]=%c\n",s[0]);
return 0;
}
结果:
&i=000000000065FE3C
s =0000000000429000
s2=0000000000429000
here!s[0]=H
- s是一个指针,初始化为指向一个字符串常量
- 由于这个常量所在的地方,所以实际上s是 const char* s ,但是由于历史的原因,编译器接受不带const的写法
- 但是试图对s所指的字符串做写入会导致严重的后果
- 如果需要修改字符串,应该用数组:
- char s[] = "Hello,world!";
指针还是数组?
char *str = "Hello";char world[] = "Hello";
- 数组:这个字符串在这里
- 作为本地变量空间自动被回收
- 指针:这个字符串不知道在哪里
- 处理参数
- 动态分配空间
- 如果要构造一个字符串-->数组//存疑?
- 如果要处理一个字符串-->指针//存疑?
- 作为本地变量空间自动被回收