c - 在 C 中, printf ("Hello") 如何在任何情况下输出 "Cello"?

标签 c string

我完全想念 printf("Hello") ever 怎么打印 Cello。它挑战了我对 C 的基本理解。但是从 Stack Overflow 上以下问题的最佳答案(Carson Myers)看来,这似乎是可能的。你能用简单的术语解释一下这怎么可能吗?答案如下:

Whenever you write a string in your source, that string is read only (otherwise you would be potentially changing the behavior of the executable--imagine if you wrote char *a = "hello"; and then changed a[0] to 'c'. Then somewhere else wrote printf("hello");. If you were allowed to change the first character of "hello", and your compiler only stored it once (it should), then printf("hello"); would output cello!)

上述问题:Is it possible to modify a string of char in C?

最佳答案

原因:

  1. 编译器通常只存储相同字符串文字的一份副本,因此 char *a = "hello"; 中的字符串文字在printf("hello")可以在相同的内存位置。

  2. 您链接中的答案假设用于存储字符串文字的内存位置是可变的,这在现代架构中通常不是。然而,如果没有内存访问保护,这是正确的,例如在某些嵌入式体系结构中或在实模式下工作的 80386。

  3. 所以当你修改a引用的字符串时, printf 的值也有变化。

关于c - 在 C 中, printf ("Hello") 如何在任何情况下输出 "Cello"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26546740/

相关文章:

ruby - Ruby 字符串的 gsub 和 sub 方法有什么区别

C : Store and index a HUGH amount of info! 学校项目

c++ - 连接到网络的所有设备的列表

c - __attribute__((OS_main)) 在 AVR 中导致奇怪的行为

C 中基本 TCP 客户端服务器编程中的连接错误

Char* 数组不保留值 C

regex - 使用正则表达式拆分字符串并将其存储到数据框中

c - 从字符串中提取子字符串时出现意外行为

c++将字符串转换为参数中的LPCWSTR

c++ - 将字符串作为字节序列写入文件