tyr*_*na4 -1 c pointers const segmentation-fault
假设我在C中声明了这个变量:
const char*** const strings;
Run Code Online (Sandbox Code Playgroud)
现在如果我试试这个:
printf("character is : %c \n",***strings);
**strings="hello";
printf("strings is %s \n", **strings);
printf("character is : %c \n",***strings);
Run Code Online (Sandbox Code Playgroud)
有时,我得到以下输出:
character is :
strings is hello
character is : h
Run Code Online (Sandbox Code Playgroud)
但是有时我会得到一个段错误,因为(我假设)该指令
**strings="hello";
Run Code Online (Sandbox Code Playgroud)
我认为你可以用char* str = "hello";C语言编写,使str指向一个不可修改的字符串"hello".为什么这不适用于我的情况?任何人都可以解释为什么它不会给出相同的输出evertime?
当你写:
const char*** const strings;
Run Code Online (Sandbox Code Playgroud)
您要求编译器分配指向字符串指针的指针.
它确实如此,仅此而已:
因此,当您通过解除引用来使用它时,您实际上是在读取/写入随机内存,并且它是否崩溃是随机的.
写这个会改为:
char* empty = "";
char** pointer = ∅
char*** strings = &pointer;
Run Code Online (Sandbox Code Playgroud)
你的评论表明你不太熟悉const的工作方式,所以让我解释一下:
const char*** const strings;
Run Code Online (Sandbox Code Playgroud)
不是完全只读.它看起来像这样:
(constant pointer) -> (pointer) -> (pointer) -> (constant char)
Run Code Online (Sandbox Code Playgroud)
因此,您可以修改中间指针(*字符串和**字符串).
如果你想要一个完全只读的指针,写下这个:
const char const * string = "hello";
const char const * const * string_pointer = &string;
const char const * const * const * string_pointer_pointer = &string_pointer;
Run Code Online (Sandbox Code Playgroud)
你不能再修改任何东西了.