由书写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" 了。

 

 

posted @ 2015-08-13 23:38  站在边缘的人  阅读(214)  评论(0编辑  收藏  举报