【发布时间】:2016-09-04 21:18:19
【问题描述】:
我已经阅读了诸如why a pointer can be assigned value? 之类的问题的答案,但是我对更改指针的值仍然有些困惑。一些 cmets 似乎并不完全准确,或者它可能是特定于实现的。 (例如:a[1] is exactly the same as writing *(a + 1). Obviously you can write *a = 3 since a is int*, so you can also write *(a + 1) = 3, so you can also write a[1] = 3)。
编写*a = 3 会产生警告:初始化使指针从整数而不进行强制转换。还有一个段错误。
我的问题如下。
int main(void)
{
int b = 5, c = 10;
int *a = b;
*a = c; /* Will not work. (Should technically change the value of b to 10, leaving the pointer still pointing to b.) */
printf("%d\n", *a);
return 0;
}
上面的例子不起作用,并且会产生一个段错误,但由于某种我不知道的原因,下面的例子起作用了。
int main(void)
{
int a[10], i;
for (i = 0; i < 10; ++i) {
*(a + i) = i; /* Supposedly the same logic as '*a = c;', but works*/
}
for (i = 0; i < 10; ++i) {
printf("%d\n", *(a + i));
}
return 0;
}
感谢您的时间和努力。
**编辑:谢谢你的回答,因为它是 *a = &b (我知道这个(错字),但现在循环的第二个例子不清楚),数组索引被视为变量,而不是我假设的地址?
【问题讨论】:
-
*具有三种不同的含义,具体取决于使用它们的上下文。见stackoverflow.com/questions/36962658/…。 -
不要忽略编译器警告。警告是错误,除非您可以证明。讨论一个编译错误的程序做什么是没有意义的。
-
*a = 3;不会发出警告。此外,*a = 3;不会出现在您的代码中。*a = c;是正确的,没有给出警告。我猜你在练习中写了int *a = 3;,并没有意识到这与*a = 3;不同。 -
第二个例子有什么不清楚的地方?
-
现在很清楚了。谢谢@M.M