为什么char*被视为与C中的char**相同​​?

aus*_*ton 5 c arrays pointers character-arrays

我有以下测试应用程序:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main(void){
    char buf[512];
    buf[0]= 0x1;
    buf[1]= 0x2;
    char *temp1 = &buf;
    char *temp2 = buf;
    char *temp3 = &buf[0];
    printf("temp1:%p, temp2:%p, temp3:%p\n",temp1,temp2,temp3);
    printf("0 = %d, %d, %d\n",temp1[0],temp2[0],temp3[0]);
    printf("1 = %d, %d, %d\n",temp1[1],temp2[1],temp3[1]);
    return;
}
Run Code Online (Sandbox Code Playgroud)

它汇编了一个警告:

gcc ./testptr.c -o testptr
./testptr.c: In function ‘main’:
./testptr.c:9: warning: initialization from incompatible pointer type
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,所有三个指针的行为都相同.

./testptr
temp1:0x7fff3a85f220, temp2:0x7fff3a85f220, temp3:0x7fff3a85f220
0 = 1, 1, 1
1 = 2, 2, 2
Run Code Online (Sandbox Code Playgroud)

我知道buf == &buf[0],但为什么&buf == &buf[0]呢?不&buf应该是char**

hug*_*omg 3

所有指针的行为都相同,因为您将它们全部声明为char*. C 是静态类型的,因此类型绑定到变量而不是值。

现在已经解释了行为部分,我们只需要找出为什么它们实际上具有相同的值(根据 %p printf)。好吧,这只是 GCC 将指针实现为内存地址的产物(使 * 与 ** 不同的偏移量和大小都由幕后的类型系统/编译器处理)。请注意,就像任何发出警告的最可疑的东西一样,这可能是未定义的行为,或者至少是一种不好的做法:)