从C语言字符串说起

快速开始

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(){
char buf[]={'a','b','c','\0'};
char *p1 = "hello,world!";
char *p2 = (char*)malloc(100);
strcpy(p2,"hello,world2!");
printf("%s\n",buf);
printf("%s\n",p1);
printf("%s\n",p2);
}

以上代码输出结果:

1
2
3
abc
hello,world!
hello,world2!

输出结果并没有什么区别,但是这里三个字符串却分别使用了三种不同类型的内存空间,第6行代码,申请了栈区的内存空间,并将字符a,b,c依次存到了所申请的内存空间。

第7行,在栈区申请了4个字节的内存空间(变量p1),并把p1指向字符串”hello,world!”所在的内存首地址。那么,”hello,world!”存在什么地方呢?答案是,存在了全局区。

第8行,在栈区分配了4个字节的内存空间(变量p2),在堆区分配了100个字节的空间,把p指向堆区空间的首地址,第9行,往堆区申请的内存空间拷贝了字符串”hello,world2!”

尝试改变三个字符串的其中一个字符,我们,发现,全局区的字符串不让修改,其它两个区的修改,没有问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(){
char buf[] ={'a','b','c','\0'};
char * p1 = "hello,world!";
char * p2 = (char *)malloc(100);
strcpy(p2, "hello,world2!");
printf("%s\n", buf);
printf("%s\n", p1);
printf("%s\n", p2);
printf("=================================\n");
buf[1] = 'd';
printf("%s\n", buf);
//printf("=================================\n");
//p1[1]='d';//Segmentation fault
//printf("%s\n",p1);
printf("=================================\n");
p2[1] = 'd';
printf("%s\n", p2);
}

我们可以看出,关于C语言的字符串,保存在不同的内存区,进行相同的操作,结果是不一样的,可以说,学习C语言的精髓,就是学习如何操作内存,随时明白自己当下在操作的内存区域的特点。后面我们将会陆续跟进内存四区的研究。