900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > C语言字符串指针和字符串数组的区别

C语言字符串指针和字符串数组的区别

时间:2024-06-04 19:01:26

相关推荐

C语言字符串指针和字符串数组的区别

C语言里的指针、数组、字符串等等这些东西在我编程入门的时候一直捋不清楚,而为什么捋不清楚,是因为我不知道程序运行时内存是怎么分区的,更不知道这些变量啊、常量啊究竟是放在内存里的什么地方。所以说,想清晰地认识指针和数组的区别,得先了解一下程序运行时内存的分区、变量存放位置。

C语言程序运行时的内存分为以下5个区,详细可看这篇博客: /shulianghan/article/details/20472269

栈区 (stack): 存放内容 : 局部变量, 参数;

堆区 (heap): 存放内容 : 存放程序运行中 动态分配 内存的数据;

全局区/静态区: 存放内容 : 全局变量, 静态变量;

常量区: 存放内容 : 常量; (比如char *s = “hello”,此处的hello就存储在常量区)

代码区(text segment) : 存放内容 : 存放函数体的二进制代码。

打印一下看看各个区的地址,代码如下:

#include <stdio.h>#include <stdlib.h>int globalVar1 = 1; //全局变量int main(){static int staticVar1 = 1; //静态变量int stackVar1 = 1;//栈变量int *pHeap1 = (int *)malloc(sizeof(int));//指向堆的指针if(!pHeap1) {printf("error\n");return -1;}*pHeap1 = 1;char *pConstant1 = "hello 1"; //指向常量的指针printf("全局变量的地址: %p\n", &globalVar1);printf("静态变量的地址: %p\n", &staticVar1);printf("栈变量的地址: %p\n", &stackVar1);printf("堆变量的地址: %p\n", pHeap1);printf("字符常量的地址: %p\n", pConstant1);return 0;}

运行结果:

可见全局变量和静态变量是放在同一区域。

知道了各个区的地址后,我们就可以来看看字符串指针和字符串数组的区别了。

声明一个指针和数组,代码如下:

#include <stdio.h>#include <stdlib.h>int globalVar1 = 1; //全局变量int main(){static int staticVar1 = 1; //静态变量int stackVar1 = 1;//栈变量int *pHeap1 = (int *)malloc(sizeof(int));//指向堆的指针if(!pHeap1) {printf("error\n");return -1;}*pHeap1 = 1;char *pConstant1 = "hello 1"; //指向常量的指针printf("全局变量的地址: %p\n", &globalVar1);printf("静态变量的地址: %p\n", &staticVar1);printf("栈变量的地址: %p\n", &stackVar1);printf("堆变量的地址: %p\n", pHeap1);printf("字符常量的地址: %p\n", pConstant1);printf("---------------------------\n");char *pChar = "hello world"; //字符串指针char array[] = "hello world";//字符串数组printf("指针pChar的地址: %p\n", &pChar);printf("数组array的地址: %p\n", array);printf("pChar指向字符串的第一个字母'h'的地址': %p\n", pChar);printf("array第一个字母'h'的地址: %p\n", &array[0]);return 0;}

运行结果:

可见:

pChar是一个存放在栈区的字符串指针,而它的值,是一个地址,该地址指向存放在常量区的字符串;

array是一个存放在栈区的字符串数组,而它的值,就是字符串本身。

示意图如下:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。