C双指针的数组符号等价

时间:2016-10-22 19:32:25

标签: c arrays pointers

如果我有以下双指针并且我以数组形式使用它,那么所提到的指针形式是否相当于?

char** argv = malloc(2*sizeof(char*));

//argv[0] == (argv + 0), *(argv + 0), or (*argv + 0)?

//Same way, what would argv[0][0] be equivalent to in terms of *(*(argv +i)+j), etc.?

1 个答案:

答案 0 :(得分:0)

  

//argv[0] == (argv + 0), *(argv + 0), or (*argv + 0)?

好的,*(argv + 0)(*argv + 0)都等同于argv[0]。通过打印输出可以很容易地知道这一点。你可以这样做:

char** argv = malloc(2*sizeof(char*));

for(int i = 0; i < 2; i++){
    argv[i] = malloc(1);
}

//printing the values:
printf("%p == %p\n", argv[0], argv + 0);
printf("%p == %p\n", argv[0], *(argv + 0));
printf("%p == %p\n", argv[0], *argv + 0);

<强>输出:

0x8e84018 == 0x8e84008 //not equal
0x8e84018 == 0x8e84018 //same
0x8e84018 == 0x8e84018 //same

请点击此处查看完整示例:https://ideone.com/DDXuI9

(argv + 0)的情况下不正确,因为(argv + 0)指向char** argv本身的地址,而argv[0]指向第一个地址element (类型为char*