【发布时间】:2013-01-15 03:18:12
【问题描述】:
#include <stdio.h>
int main(void){
char *p = "Hello";
p = "Bye"; //Why is this valid C code? Why no derefencing operator?
int *z;
int x;
*z = x
z* = 2 //Works
z = 2 //Doesn't Work, Why does it work with characters?
char *str[2] = {"Hello","Good Bye"};
print("%s", str[1]); //Prints Good-Bye. WHY no derefrencing operator?
// Why is this valid C code? If I created an array with pointers
// shouldn't the element print the memory address and not the string?
return 0;
}
我的问题与 cmets 一起列出。在一般情况下,我无法理解字符数组和指针。特别是为什么我可以在没有取消引用运算符的情况下访问它们。
【问题讨论】:
-
对于 str[1],会发生解除引用。在内部它将像 *(str + 1)
-
来到 p = "Bye" 实际上 p 是指向常量的指针,所以如果你喜欢 *p = 'a';它不会在编译时允许你,但因为你做了 p = "Bye" ,它会给 p 一个新地址所以它会工作
-
@user93353。我确实买了一本书。此代码来自一本书。感谢您富有洞察力的 cmets。不是
-
这本书没有解释发生了什么?
-
你需要买一本更好的书——也许是 Kernighan 和 Ritchie?也许其中之一 - stackoverflow.com/questions/693210/…
标签: c arrays pointers character