RSA*_*RSA 3 c string pointers constants string-constant
为什么这样可以:
char a[2];
a[0] = 'a';
const char *b;
b = a;
printf("%s\n", b);
a[0] = 'b';
printf("%s", b);
Run Code Online (Sandbox Code Playgroud)
为什么指向常量字符串的指针可以指向非常量字符串?另外,将字符串常量分配给变量时如何工作?为什么你可以这样做:
const char *b = "hello";
b ="test";
Run Code Online (Sandbox Code Playgroud)
或者
char *b = "hello";
b = "test";
Run Code Online (Sandbox Code Playgroud)
但如果它是一个数组,你只能做第一行?恒定与否?
为什么我可以有一个
const char *指向可变char数组的点?
下面对其使用进行const了b限制。它不允许一些新的用途,但可能会更少。所以这里没有打开潘多拉魔盒。
char a[2];
const char* b = a;
Run Code Online (Sandbox Code Playgroud)
b具有对该数组的读取访问权限。该数组a[]仍可能通过 进行更改a。
a[0]='y'; // OK
b[0]='z'; // leads to error like "error: assignment of read-only location "
Run Code Online (Sandbox Code Playgroud)
另外,将字符串常量分配给变量时如何工作?恒定与否?
"hello"是类型的字符串文字char [6]。通过const char* b1 = "hello"声明和初始化,b1分配一个类型为 的指针char *。这本来是可能的const char *,但由于历史原因1确实如此char *。既然是char*,char* b2 = "hello";也行。
const char* b1 = "hello";
char* b2 = "hello";
Run Code Online (Sandbox Code Playgroud)
另外,将字符串常量分配给变量时如何工作?
b="test";
Run Code Online (Sandbox Code Playgroud)
作为赋值的一部分,字符串文字(一个char数组)被转换为其第一个元素 a 的地址和类型char *。该指针被分配给b。
1 const在早期的 C 中不可用,因此为了不破坏现有的代码库,字符串文字仍然没有const.