小工具知识网

当前位置: 首页 > 行业知识 > 【C语言】字符指针

行业知识

【C语言】字符指针

2026-11-14 01:14:34 来源:互联网转载

在index.php/tags-41973.html" >���针的类型中我们知道有一种指针类型为字符指针char*

一般使用:

int main(){char ch = 'w';char *pc = &ch;*pc = 'w';return 0;}

还有一种使用方式,如下:

int main(){const char* pstr = "hello bit.";//这⾥是把⼀个字符串放到pstr指针变量⾥了吗?printf("%s\n", pstr);return 0;}

代码 const char* pstr = "hello bit.";特别容易让大家以为是把字符串 hello bit 放到字符指针 pstr 里了,但是本质是把字符串 hello bit. 首元素的地址放到 pstr 中。

 上⾯代码的意思是把⼀个常量字符串的⾸字符 h 的地址存放到指针变量 pstr 中。

《剑指offer》中收录了⼀道和字符串相关的笔试题,我们⼀起来学习⼀下:

#include int main(){char str1[] = "hello bit.";char str2[] = "hello bit.";const char *str3 = "hello bit.";const char *str4 = "hello bit.";if(str1 ==str2)printf("str1 and str2 are same\n");elseprintf("str1 and str2 are not same\n");if(str3 ==str4)printf("str3 and str4 are same\n");elseprintf("str3 and str4 are not same\n");return 0;}

输出结果,如下:

这⾥str3和str4指向的是⼀个同⼀个常量字符串。C/C++会把常量字符串存储到单独的⼀个内存区域,当几个指针指向同⼀个字符串的时候,他们实际会指向同⼀块内存。但是用相同的常量字符串去初始化不同的数组的时候就会开辟出不同的内存块。所以str1和str2不同,str3和str4相同。

 

上一篇:服务器怎么电脑远程?

下一篇:web在线编辑器(vue版)