首页 > 解决方案 > Array 和 Array[0] 混淆

问题描述

在以下 C 代码中:

char test[] ={'T','e','s','t'};

printf("%d\n",test == &test[0]); // Returns 1 - Okay as array varaible holds address of first element

那么以下内容不应该打印相同的内容吗?:

printf("value of test %c\n", test); // prints - '|' not even in the array
printf("value of test[0] %c\n", test[0]); // prints - 'T'

即便如此,即使这些打印出不同的值:

printf("value of test %p\n", test); // contains a address 0x7ffee9b22b7c
printf("value of test[0] %p\n", test[0]); // also conatains 0x100

怎么了?

谢谢

标签: carrayspointerspointer-to-array

解决方案


您在第一个示例中回答了您自己的问题:

test == &test[0]

test != test[0] // otherwise, test[0] would have to be equal to &test[0]

即(解释为指针)的等于的地址。因此,您的以下示例不可能是正确的,因为这意味着对于其中任何一个,它的值都将等于它自己的地址,这是没有意义的!testtest[0]

(注:以下地址当然是示例。)

表达 类型 值解释为字符%c 值解释为指针%p
test char* 荒谬的 0x1000
&test char** 荒谬的 0x2000
test[0] char T 荒谬的
&test[0] char* 荒谬的 0x1000
test[1] char e 荒谬的
&test[1] char* 荒谬的 0x1001
test[2] char s 荒谬的
&test[2] char* 荒谬的 0x1002
test[3] char t 荒谬的
&test[3] char* 荒谬的 0x1003

注意:为了理解您最初的问题,可以将test视为char*,因此&test视为char**。然而,实际上它有点复杂,test实际上是 type char(*)[4]。例如,这会有所不同sizeof


推荐阅读