c语言中常量字符串赋值给数组与指针的区别

1、代码

#include <stdio.h>
int main()
{
    char str1[] = "hello word!!";
    char str2[] = "hello word!!";
    const char *str3 = "hello word!!";
    const char *str4 = "hello word!!";
    if(str1 == str2){
        printf("str1 and str2 are same\n");
	}
    else{
		printf("str1[0]=%c\n",str1[0]);
		printf("str2[0]=%c\n",str2[0]);
		printf("str1=%p\n",str1);
		printf("str2=%p\n",str2);
        printf("str1 and str2 are not same\n");
	} 
    if(str3 ==str4){
       printf("str3=%p\n",str3);
	   printf("str4=%p\n",str4);
       printf("str3 and str4 are same\n");
	}
    else{
     printf("str3 and str4 are not same\n");
    }
    return 0; 
}

打印:

str1[0]=h
str2[0]=h
str1=0x7ffcc87b0a80
str2=0x7ffcc87b0a90
str1 and str2 are not same

str3=0x7ffcc87b0111
str4=0x7ffcc87b0111
str3 and str4 are same

2、解析

仔细看发现str1=0x7ffcc87b0a80和str2=0x7ffcc87b0a90地址是不同的,常量字符串去初始化不同的数组的时候就会开辟出不同的内存块,此时地址已经不一样了,如果是对指针初始化,实际会指向同一块常量字符串内存,地址是一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那肯定是很多年以后!

你的鼓励就我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值