通过 C 中的非常量指针更改常量内存内容

标签 c pointers segmentation-fault constants

假设我在 C: 中声明此变量

const char*** const strings; 

现在如果我尝试这个:

printf("character is : %c \n",***strings);

**strings="hello";

printf("strings is %s \n", **strings);

printf("character is : %c \n",***strings);

有时,我会得到以下输出:

character is :
strings is hello
character is : h

但是有时我会遇到段错误,因为(我假设)指令

**strings="hello";

我认为你可以用C编写char* str = "hello";,使str指向一个不可修改的字符串“hello”。 为什么这在我的情况下不起作用? 谁能解释为什么它不总是给出相同的输出?

最佳答案

当你写下:

const char*** const strings;

您要求编译器分配一个指向字符串指针的指针。

它确实做到了这一点,仅此而已:

  • 它不会分配字符串或指向字符串的指针。
  • 它不会将值初始化为任何特定值。

因此,当您通过取消引用来使用它时,您实际上是在随机读取/写入一 block 内存,并且它是否崩溃是随机的。

写这个会起作用:

char* empty = "";
char** pointer = ∅
char*** strings = &pointer;

您的评论表明您不太熟悉 const 的工作原理,所以让我解释一下:

const char*** const strings;

不是完全只读的。它看起来像这样:

(constant pointer) -> (pointer) -> (pointer) -> (constant char)

因此您可以修改中间指针(*strings 和 **strings)。

如果您想要一个完全只读的指针,请编写以下内容:

const char const * string = "hello";
const char const * const * string_pointer = &string;
const char const * const * const * string_pointer_pointer = &string_pointer;

并且您不再可以修改任何内容。

关于通过 C 中的非常量指针更改常量内存内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890589/

相关文章:

objective-c - 指针和opengl绘图的问题

c++ - 与动态内存分配 C++ 混淆

c++ - 大输入的段错误

C 程序错误 - 段错误(核心已转储)

c++ - C/C++ : Why the localtime display incorrectly in respect of its timezone?

c - 程序只读取 C 中 Matrix 的第一行

C 代码循环性能 [续]

c++ - 排列程序无法写入数组 - 运行时错误

c - 使用 C 预处理器读取变量

python - PyOpenCl:如何调试段错误?