我已閱讀why a pointer can be assigned value?等問題的答案,但是我仍然對改變指針值有點困惑。有些評論似乎並不完全準確,或者可能是特定於實施的。 (例如: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
)。爲什麼未初始化的指向int數組的指針被分配變量的值?
寫入*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(我知道這個(錯字),但現在循環的第二個例子不清楚),數組索引被視爲變量,不是我認爲的地址?
'int * a =&b;'。 – user3386109
'*'有三種不同的含義,它們取決於它們的使用環境。請參閱http://stackoverflow.com/questions/36962658/what-exactly-is-the-purpose-of-the-asterisk-in-pointers/36962697#36962697。 –
不要忽略編譯器警告。警告是錯誤的,除非你能證明*否則。討論具有編譯錯誤的程序是沒有意義的。 –