Char *p1 = “A String.” 和 char p2[] = “another String.” 写法的不同
p1指向的这个字符串是个常量, 不可改变。 程序在编译期间就为"A String."这个字符串分配了固定的空间, 它被存储在全局静态区中. 编译器只是把指针p1的指向的地址赋为“A String.”的首地址,并没有为指针p1指向的地址分配可供操作的内存(除非使用malloc),如果试图改变p1指向的字符串,则会出错(试图改变不可写内存内容的错误)。
而p2是个变量, 其内容可以被更新和改变, p2可以理解为一个不可改变其指向位置的指针, 即char * const p2, 它所占用的内存在程序运行时被自动分配和释放, 而p1占用的内存要等到整个程序结束时才被释放. 编译器为数组b分配了可供操作的存储空间.
- #include <stdio.h>
- void main()
- {
- void copy_string(char *si, char *di);
- char *ss,*dd;
- char from[] = "I am a student.";
- char to[] = "You are a teacher.";
- ss = "I am a student.";
- dd = "You are a teacher.";
- printf("a:%s/nb:%s/n",ss,dd);
- copy_string(ss,to); //这样写没有问题
- //copy_string(ss,dd); //有问题
- //copy_string(from,to);//没问题
- printf("/n");
- printf("a:%s/nb:%s/n",ss,to);
- }
- void copy_string(char *si, char *di)
- {
- for(; *si != '/0'; si++,di++)
- *di = *si;
- *di = '/0';
- }