char型指针和字符串字面量和字符数组

1、当一个char型指针指向一个字符串字面量(也就是常量字符串)时,该指针必须由const修饰,否则,系统会给出deprecated(不赞成)的警告。原因是:字符串字面量不可改变,当它被一个非const修饰的指针指向时,存在被指针改变的风险。

2、char型指针指向一个字符数组时,没有const限制,因为字符数组可以被改变。但是,如果我们不需要指针来改变字符数组时,我们最好加上const修饰,来限制指针的行为,减少出错的概率。

3、例子:

#include <cstdio>
int main(){
    char *p;
    p="where";
    puts(p);
    return 0;
}
编译后:t3.cpp: In function ‘int main(int, char**)’:
t3.cpp:5:3: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  p="where";
   ^
#include <cstdio>
int main(int argc, char *argv[])
{
    const char *p;
    char c[20]="where are you";
    p=c;
    puts(p);

    return 0;
}
//该程序换为数组,则没有任何问题

猜你喜欢

转载自www.cnblogs.com/litifeng/p/9006175.html