char pointers and string literals and character arrays

1. When a char type pointer points to a string literal (that is, a constant string), the pointer must be modified by const, otherwise, the system will give a deprecated (disapproved) warning. The reason is: the string literal is immutable, and when it is pointed to by a non-const-modified pointer, there is a risk of being changed by the pointer.

2. When a char pointer points to a character array, there is no const restriction, because the character array can be changed. However, if we don't need pointers to change character arrays, we'd better add const modifiers to limit the behavior of pointers and reduce the probability of errors.

3. Example:

#include <cstdio>
int main(){
    char *p;
    p="where";
    puts(p);
    return 0;
}
After compilation: 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;
}
// The program is replaced with an array, there is no problem

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325877123&siteId=291194637