我完全想念 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!)
最佳答案
原因:
编译器通常只存储相同字符串文字的一份副本,因此
char *a = "hello";
中的字符串文字在printf("hello")
可以在相同的内存位置。您链接中的答案假设用于存储字符串文字的内存位置是可变的,这在现代架构中通常不是。然而,如果没有内存访问保护,这是正确的,例如在某些嵌入式体系结构中或在实模式下工作的 80386。
所以当你修改
a
引用的字符串时,printf
的值也有变化。
关于c - 在 C 中, printf ("Hello") 如何在任何情况下输出 "Cello"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26546740/