Ice*_*man 153 c pointers const
有什么区别
char* name
Run Code Online (Sandbox Code Playgroud)
它指向一个常量字符串文字,和
const char* name
Run Code Online (Sandbox Code Playgroud)
ank*_*sra 357
char*是一个指向可变字符/字符串的可变指针.
const char*是一个指向不可变字符/字符串的可变指针.您无法更改此指针指向的位置的内容.此外,编译器在尝试执行此操作时需要提供错误消息.出于同样的原因,从转换到已被弃用.const char *char*
char* const是一个不可变的指针(它不能指向任何其他位置),但它指向的位置的内容是可变的.
const char* const是一个指向不可变字符/字符串的不可变指针.
Alo*_*ave 41
char *name
Run Code Online (Sandbox Code Playgroud)
您可以将char更改为哪个name点,以及它指向的char.
const char* name
Run Code Online (Sandbox Code Playgroud)
您可以将char更改为哪些name点,但不能修改它指向的char.
更正:您可以更改指针,但不能更改指向的字符name(https://msdn.microsoft.com/en-us/library/vstudio/whkd4k6a(v=vs.100).aspx,请参阅"示例" ).在这种情况下,说明const符适用于char星号而不是星号.
根据MSDN页面和http://en.cppreference.com/w/cpp/language/declarations,const前面*是decl-specifier序列的一部分,而constafter *是声明符的一部分.
声明说明符序列后面可以跟多个声明符,这就是const char * c1, c2声明c1as const char *和c2as的原因const char.
编辑:
从注释中,您的问题似乎是在指针指向字符串文字时询问两个声明之间的区别.
在这种情况下,您不应该将char修改为哪些name点,因为它可能导致未定义的行为.字符串文字可以在只读存储器区域中分配(实现定义),并且用户程序不应该以任何方式修改它.任何这样做的尝试都会导致未定义的行为.
因此,在这种情况下(使用字符串文字)的唯一区别是第二个声明给你一点点优势.如果您尝试在第二种情况下修改字符串文字,编译器通常会给您一个警告.
#include <string.h>
int main()
{
char *str1 = "string Literal";
const char *str2 = "string Literal";
char source[] = "Sample string";
strcpy(str1,source); //No warning or error, just Undefined Behavior
strcpy(str2,source); //Compiler issues a warning
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
cc1:警告被视为错误
prog.c:在函数'main'中:
prog.c:9:错误:传递'strcpy'的参数1从指针目标类型中丢弃限定符
请注意,编译器会警告第二种情况,但不会警告第一种情况.
Afr*_*ief 15
char mystring[101] = "My sample string";
const char * constcharp = mystring; // (1)
char const * charconstp = mystring; // (2) the same as (1)
char * const charpconst = mystring; // (3)
constcharp++; // ok
charconstp++; // ok
charpconst++; // compile error
constcharp[3] = '\0'; // compile error
charconstp[3] = '\0'; // compile error
charpconst[3] = '\0'; // ok
// String literals
char * lcharp = "My string literal";
const char * lconstcharp = "My string literal";
lcharp[0] = 'X'; // Segmentation fault (crash) during run-time
lconstcharp[0] = 'X'; // compile error
// *not* a string literal
const char astr[101] = "My mutable string";
astr[0] = 'X'; // compile error
((char*)astr)[0] = 'X'; // ok
Run Code Online (Sandbox Code Playgroud)
在任何情况下都不能修改字符串文字,无论指向该字符串文字的指针是否声明为char *或const char *.
但是,区别在于,如果指针是,const char *则编译器必须提供诊断,如果您尝试修改指向的值,但如果指针是,char *那么它不会.
小智 6
情况1:
char *str = "Hello";
str[0] = 'M' //Warning may be issued by compiler, and will cause segmentation fault upon running the programme
Run Code Online (Sandbox Code Playgroud)
上面将 str 设置为指向硬编码在程序二进制图像中的文字值“Hello”,在内存中标记为只读,这意味着此字符串文字的任何更改都是非法的,并且会引发分段错误。
案例2:
const char *str = "Hello";
str[0] = 'M' //Compile time error
Run Code Online (Sandbox Code Playgroud)
案例3:
char str[] = "Hello";
str[0] = 'M'; // legal and change the str = "Mello".
Run Code Online (Sandbox Code Playgroud)