我试图用指针理解一些东西,所以我写了以下代码:

#include <stdio.h>

int main(void)
{
    char s[] = "asd";
    char **p = &s;

    printf("The value of s is: %p\n", s);
    printf("The direction of s is: %p\n", &s);

    printf("The value of p is: %p\n", p);
    printf("The direction of p is: %p\n", &p);

    printf("The direction of s[0] is: %p\n", &s[0]);
    printf("The direction of s[1] is: %p\n", &s[1]);
    printf("The direction of s[2] is: %p\n", &s[2]);

    return 0;
}

使用gcc编译时,我会收到以下警告:

$ gcc main.c -o main-bin -ansi -pedantic -Wall -lm
main.c: In function ‘main’:
main.c:6: warning: initialization from incompatible pointer type
main.c:9: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char (*)[4]’
main.c:11: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char **’
main.c:12: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘char ***’

(gcc的标志是因为我必须是C89)

为什么指针类型不兼容?数组的名称不是指向它的第一个元素的指针吗?所以如果s是指向a的指针,&s一定是char **,不是吗?

run 时我会得到这样的结果:

$ ./main-bin
The value of s is: 0xbfb7c860
The direction of s is: 0xbfb7c860
The value of p is: 0xbfb7c860
The direction of p is: 0xbfb7c85c
The direction of s[0] is: 0xbfb7c860
The direction of s[1] is: 0xbfb7c861
The direction of s[2] is: 0xbfb7c862

s的值和它的方向(当然还有p的值)怎么会相同呢?

推荐答案

"s"不是"char*",而是"char[4]".因此,"&;s"不是"char**",而实际上是"指向4个字符的数组的指针".您的编译器可能会将"&;s"视为您编写的"&;s[0]",这大致相同,但是是一个"char*".

When you write "char** p = &s;" you are trying to say "I want p to be set to the address of the thing which currently points to "asd". But currently there is nothing which points to "asd". There is just an array which holds "asd";

char s[] = "asd";
char *p = &s[0];  // alternately you could use the shorthand char*p = s;
char **pp = &p;

C++相关问答推荐

C++ cout打印顺序与C print相比

ARM上的Modulo Sim Aarch 64(NEON)

问关于C中的指针和数组

在#include中使用C宏变量

__VA_OPT__(,)是否可以检测后面没有任何内容的尾随逗号?

如何在不使用其他数组或字符串的情况下交换字符串中的两个单词?

为什么我不能只在内存地址中添加一个int来寻址任何数组?

Clang警告称,`ffi_type`与`sizeof`不兼容

使用错误的命令执行程序

Flose()在Docker容器中抛出段错误

GDB输出ARM助记符

在移动数组元素时获得意外输出

使用ld将目标文件链接到C标准库

C-try 将整数和 struct 数组存储到二进制文件中

如何在zOS上编译共享C库

如何摆脱-WIMPLICIT-Function-声明

如何在C宏定义中包含双引号?

c如何传递对 struct 数组的引用,而不是设置 struct 的副本

将数组返回到链表

快速准确计算double的小数指数