C语言学习笔记——字符串操作

char heart[] = "I am the heart";char *head = "I am the head";
若想让heart和head统一,可以执行如下操作:
head = heart; // 指针head指向了数组heart
但以下操作是非法的:
heart = head;// heart为地址常量,不能作为左值
part2 以下未使用const限定的指针初始化:
char *word = "frame";
是否可以使用该指针来修改该字符串?
word[1] = 'l'; // 是否允许?
《CPlus》中是这样描述的:编译器可能允许这样做,但是对于当前的C标准而言,这样的行为是未定义的 。列如,这样的语句可能导致内存访问错误 。原因:编译器可以使用内存中的一个副本来表示所有完全相同的字符串字面量 。参见如下示例(错误示例):
/** BUGGY: Segmentation fault (core dumped)* str_constant_pt.c -- 使用指针修改字符串常量 */#include int main(void) {char *p1 = "Klingon";p1[0] = 'F';printf("Klingon");printf(": Beware the %ss!\n", "Klingon");return 0;}
原书中显示的结果是:
Flingon: Beware the Flingons!
而我自己的自行结果如下:
[root@gavinpan p2]# !ggcc -o str_constant_pt str_constant_pt.c [root@gavinpan p2]# !../str_constant_pt Segmentation fault (core dumped)
fault (core )多为内存不当操作造成 。空指针、野指针的读写操作,数组越界访问,破坏常量等1 。
基于上述问题,建议在把指针初始化为字符串常量时使用const限定符:
const char *pt = "Klingon";
在把非const数组初始化为字符串常量时,不会导致类似问题,因为数组获得的是原始字符串的副本 。
因此,如果打算修改字符串,就不要用指针指向字符串常量 。
字符串数组 指向字符串的指针数组
const char *pointer_arr[3] = {"alpha", "beta", "theta"};
是一个内含3个指针的数组,在当前操作系统 8中,占用24个字节:
printf("size of pointer_arr: %d\n", sizeof(pointer_arr));
输出:
size of pointer_arr: 24
char类型数组的数组
char arrays[3][10] = {"alpha", "beta", "theta"};
是内含3个数组的数组,每个数组内含10个char类型的值,共占用30个字节:
printf("size fo arrays: %d\n", sizeof(arrays));
输出:
size fo arrays: 30
中的指针指向初始化时所用字符串常量的位置;而中的数组则存储了字符串常量的副本,故每个字符串都被存储了两次 。
基于上述两种声明方式,可以把想象为不规则数组,而则为矩形二维数组:
综上,如果要用数组表示一些列带显示的字符串,请使用指针数组;如果要改变字符串或为字符串输入预留空间,不要使用指向字符串字面量的指针 。
指针和字符串
一个例子:
/* p_and_s,c --指针和字符串 */#include int main(void) {const char *msg = "Don't be a fool!";const char *copy;copy = msg;printf("%s\n", copy);printf("msg = %s; &msg = %p; value = http://www.kingceram.com/post/%p/n", msg, &msg, msg);printf("copy = %s; © = %p; copy = %p\n", copy, ©, copy);return 0;}