我是一個編程課程的助教,有的學生做這種類型的錯誤:「地址(&)被忽略的數組/地址是gcc?
char name[20];
scanf("%s",&name);
這是不是因爲他們在學習奇怪......令人驚訝的是,除了海灣合作委員會警告,代碼工作(至少這部分)。我一直在試圖理解和我寫了下面的代碼:
void foo(int *v1, int *v2) {
if (v1 == v2)
printf("Both pointers are the same\n");
else
printf("They are not the same\n");
}
int main() {
int test[50];
foo(&test, test);
if (&test == test)
printf("Both pointers are the same\n");
else
printf("They are not the same\n");
}
編譯和執行:
$ gcc test.c -g
test.c: In function ‘main’:
test.c:12: warning: passing argument 1 of ‘foo’ from incompatible pointer type
test.c:13: warning: comparison of distinct pointer types lacks a cast
$ ./a.out
Both pointers are the same
Both pointers are the same
任何人都可以解釋爲什麼他們不一樣?
我懷疑這是因爲我無法獲得數組的地址(因爲我不能有& &x
),但在這種情況下,代碼不應該編譯。
編輯:我知道一個數組本身與第一個元素的地址是一樣的,但我認爲這與這個問題無關。例如:
int main() {
int a[50];
int * p = a;
printf("%d %d %d\n", p == a, p == &a[0], &p[0] == a);
printf("%d %d %d\n", p == &a, &p == a, &p == &a);
}
打印:
$ ./a.out
1 1 1
1 0 0
我不明白爲什麼第二行以1
開始。
你的編輯表明你認爲有一些指針與數組一起存儲。但事實並非如此。一個數組只包含*它的元素。 – 2010-05-24 00:09:39
我知道一個數組只是元素,這就是爲什麼我認爲它不應該編譯。 – dbarbosa 2010-05-24 00:14:18