下面的内容是不是arrayname总是指向C中第一个元素的指针?
int myArray[10] = {0};
printf("%d\n", &myArray); /* prints memadress for first element */
printf("%d\n", myArray); /* this prints a memadress too, shows that the name is a pointer */
printf("%d\n",sizeof(myArray)); /* this prints size of the whole array, not a pointer anymore? */
printf("%d\n",sizeof(&myArray)); /* this prints the size of the pointer */
Run Code Online (Sandbox Code Playgroud)
AnT*_*AnT 18
数组名称是数组名称.数组名称是标识整个数组对象的标识符.它不是指向任何东西的指针.
当在表达式中使用数组名称时,几乎所有上下文中的数组类型都会自动隐式转换为指向元素类型(这通常称为"数组类型衰减").结果指针是一个完全独立的临时右值.它与数组本身无关.它与数组名称无关.
不进行隐式转换时的两个例外是:运算符sizeof和一元运算符&(address-of).这正是您在代码中测试的内容.
警惕这些类型.
myArray是int[10].&myArrayis 的类型int (*)[10](指向int[10]).myArray为int *.即,类型值的myArray是int *.sizeof(myArray) == sizeof(int[10]) != sizeof(int *).推论:
myArray并且&myArray是不兼容的指针类型,并且不可互换.您无法正确分配&myArray给类型的变量int *foo.