私はプログラミング入門コースのティーチングアシスタントですが、一部の学生はこの種の誤りを犯しました。
char name[20];
scanf("%s",&name);
彼らが学んでいるので、これは驚くべきことではありません...驚くべきことは、gcc警告に加えて、コードが機能することです(少なくともこの部分)。私は理解しようとしていて、次のコードを書きました。
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
2行目が。で始まる理由がわかりません1
。