由书写strlen函数碰到的问题。

今天在自己实现strlen函数的时候碰到碰到了一个很有意思的warning:

warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
#include <stdio.h>

int strlen(char *str) {
    char *s;
    for (s=str; *s; s++);
    return s - str;
}

int main()
{
    char *s1  = "abc";
    char s2[] = "abc";
    printf("%d\n", strlen(s1));
    printf("%d\n", strlen(s2));
    return 0;
}

 

由于之前竞赛一直在回避指针,所以一直使用的是"[]" 也就是数组的方式来定义。现在使用"*"也就是指针的方式来定义的时候竟然产生warning,一时还百思不得其解。

但是我觉得,跟函数传值这里应该是没有关系的,于是我把代码删掉只剩下定义语句,再次编译。

#include <stdio.h>
int main() 
{ 
    char *s1 = "abc"; 
    return 0; 
}

没错,就是只有这个定义语句,警告依然存在。

大致理解了以下警告信息,说是弃用从字符串常量转化为char指针?看得云里雾里的,但是觉得就是不让写嘛!

于是我试着修改s1的值:

#include <stdio.h>
int main() 
{ 
    char *s1 = "abc"; 
    *s1 = "bcd"; 
    return 0; 
}

 

这会得到的是error了!

error: invalid conversion from 'const char*' to 'char' [-fpermissive]

 

于是,不让修改的值,不就是常量么!

于是我果断加上const:

#include <stdio.h>
int main()
{
    const char *s1  = "abc";
    return 0;
}

 

世界清静了!

但是为什么字符串指针必须要const修饰呢?

脑子秀逗了,很明显我们是把一个字符串常量"abc"地址赋值给s1指针,那么s1指针就应该使用const 指针来接收(规范)。

那么你要想修改的话怎么办呢?答案是数组:

#include <stdio.h>

int main()
{
    const char *s1 = "abc";
    char s2[] = "111";
    *s2 = '2';
    printf("%s\n", s2);
    return 0;
}

那么,这个时候输出的值就是 "211" 了。

 

 

转载于:https://www.cnblogs.com/marginalman/p/4728787.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值