【指针进阶01】字符指针

10 篇文章 1 订阅
8 篇文章 0 订阅

字符指针

指向字符型数据的指针变量。每个字符串在内存中都占用一段连续的存储空间,并有唯一确定的首地址。即将字符串的首地址赋值给字符指针,可让字符指针指向一个字符串。

话不多说,直接上代码

test1

int main()
{
    char ch = 'w';
    char * pc = &ch;
    const char* p = "hello bit";//"hello bit"是一个常量字符串
    
    printf("%s\n", p);
    printf("%c\n", *p);

    return 0;
}

上面这段代码打印的结果是怎么样的呢?
在这里插入图片描述

char ch = ‘w’;
char * pc = &ch;

pc是指向一个字符变量。

const char* p = “hello bit”;

如果这时候进行进行 *p = 'w';操作会样呢?答案肯定是报错,"hello bit"是一个常量字符串,存放在内存的常量。上面表达式的作用是:把常量字符串"hello bit"的第一个字符h的地址赋给p。

test2

本题出自《剑指offer》

int main()
{
    char str1[] = "abcdef";
    char str2[] = "acbdef";
    const char* str3 = "abcdef"; 
    const char* str4 = "abcdef";

    if (str1 == str2)//比较的是地址
        printf("str1 and str2 are same\n");
    else
        printf("str1 and str2 are not same\n");

    if (str3 == str4)
        printf("str1 and str2 are same\n");
    else
        printf("str1 and str2 are not same\n");
    return 0;
}

猜到结果了吗?hxd
在这里插入图片描述

const char* str3 = “abcdef”;
const char* str4 = “abcdef”;

常量字符串,不能被修改.

char str1[] = “abcdef”;
char str2[] = “acbdef”;

str1,str2分别开辟各自的空间,地址自然不相同。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值