ポインターで何かを理解しようとしていたので、次のコードを書きました。
#include <stdio.h>
int main(void)
{
char s[] = "asd";
char **p = &s;
printf("The value of s is: %p\n", s);
printf("The direction of s is: %p\n", &s);
printf("The value of p is: %p\n", p);
printf("The direction of p is: %p\n", &p);
printf("The direction of s[0] is: %p\n", &s[0]);
printf("The direction of s[1] is: %p\n", &s[1]);
printf("The direction of s[2] is: %p\n", &s[2]);
return 0;
}
gcc でコンパイルすると、次の警告が表示されます。
$ gcc main.c -o main-bin -ansi -pedantic -Wall -lm
main.c: In function ‘main’:
main.c:6: warning: initialization from incompatible pointer type
main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’
main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’
main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’
(gcc のフラグは、私が C89 でなければならないためです)
ポインターの型に互換性がないのはなぜですか? 配列の名前は最初の要素へのポインタではありませんか? s が 'a' へのポインターである場合は、 a である&s
必要がありますchar **
。いいえ? また、他の警告が表示されるのはなぜですか? ポインターを出力するには、ポインターを ( ) でキャストする必要がありvoid *
ますか?
そして実行すると、次のようなものが得られます。
$ ./main-bin
The value of s is: 0xbfb7c860
The direction of s is: 0xbfb7c860
The value of p is: 0xbfb7c860
The direction of p is: 0xbfb7c85c
The direction of s[0] is: 0xbfb7c860
The direction of s[1] is: 0xbfb7c861
The direction of s[2] is: 0xbfb7c862
s の値とその方向 (そしてもちろん の値p
) が同じになるにはどうすればよいでしょうか?