C:数组指针指向自己的地址并同时携带一个值?

时间:2015-03-14 18:27:57

标签: c arrays

我是c的新手

所以在c中, 如果我在main方法中执行以下操作,

int* a = malloc( sizeof( int ) );
a[0] = 1;
printf( "%x\n", a ); // 1d02230
printf( "%x\n", &a ); // 4bed1c00
printf( "%x\n", a[0] ); // 1
printf( "%x\n", &a[0] ); // 1d02230

这对我有意义。 但是,当我执行以下操作时,

int b[] = {1};
printf( "%x\n", b ); // 4bed1bf0
printf( "%x\n", &b ); // 4bed1bf0
printf( "%x\n", b[0] ); // 1
printf( "%x\n", &b[0] ); // 4bed1bf0

这对我来说没有意义......看起来b是一个指向自己地址的指针,它也带有值1.我怀疑它与b是静态数组有关,但怎么做我理解这个????

1 个答案:

答案 0 :(得分:4)

指针和数组不是一回事。数组衰减指向大多数情境中第一个元素的指针,但不是当它们是一元&运算符的参数时。这意味着你的第二个例子意味着:

printf( "%x\n", b );     // array name decays, 100% equivalent to &b[0]
                         //   type: int *
printf( "%x\n", &b );    // name does *not* decay, gives address of array
                         //   type: int (*)[1]
printf( "%x\n", b[0] );  // value of array element 0
                         //   type: int
printf( "%x\n", &b[0] ); // address of array element 0, same as line 1
                         //   type: int *

相比之下,你的第一个例子是:

printf( "%x\n", a );     // value of pointer a
                         //   type: int *
printf( "%x\n", &a );    // address of pointer a
                         //   type: int **
printf( "%x\n", a[0] );  // value of element pointed to by a
                         //   type: int
printf( "%x\n", &a[0] ); // address of element pointed to by a (equivalent to a)
                         //   type: int *

请注意,%x不适合用于大多数这些打印语句;你很幸运能够逃脱它,但严格来说这是不明确的行为。