指向数组的指针出错

Error with pointer to an array

我有这个代码

#include <stdio.h>

int main(void)
{
    char cad[] = "abc";

    char (*ptr)[1];

    ptr[0] = cad;

    return 0;
}

编译时抛出这个错误:

error #2168: Operands of '=' have incompatible types 'char [1]' and 'char *'.

为什么会出现这个错误?

Why this error occurs (sic)?

char cad[] = "abc";

这里,cad是一个char[4](包含字符'a''b''c''[=18=]'。)

char (*ptr)[1];

这里,ptr 是指向 char[1] 的指针。所以 ptr[0] 是一个 char[1]

在赋值表达式中

 ptr[0] = cad;

cad 衰减到 char*。所以你最终会得到不兼容的操作数,即左轴上的 char[1] 和右轴上的 char*,就像编译器错误消息告诉你的那样。

还有两件事值得一提:

  • 数组是不可赋值的,所以没有ptr[0] = ???;有效的赋值表达式,给定ptr的类型。

  • 您的代码中没有指针数组。

编译器的错误信息很清楚。

ptr 的类型是 char (*)[1]
ptr[0] 的类型是 char [1].
cadptr[0] = cad 中使用时衰减为指针。因此 RHS 的类型是 char*。您不能将 char* 分配给 char [1]

此外,

ptr[0] = ...;

导致未定义的行为,因为尚未为 ptr.

分配内存

不清楚您要完成什么。你可以这样做:

char (*ptr)[1] = malloc(sizeof(*ptr));
ptr[0][0] = cad[0];

这会将 cad 的第一个字符放入 ptr[0][0]。但是,ptr[0] 不是空终止字符串。因此,您将无法像字符串一样使用它。

我想这就是你想要做的:

#include <stdio.h>

int main(void)
{
    char cad[] = "abc";
    int n = sizeof (cad) / sizeof (cad[0]);
    char (*ptr)[n];
    ptr = &cad;
    printf("%s",*ptr);
    return 0;
}

输出:

abc

您所做的问题是:

char cad[] = "abc";
char (*ptr)[1];
ptr[0] = cad;

char 数组 cad 有 "abc",类型为 char 的指针数组,然后您尝试分配指针数组的单个索引(这是一个 char) 与 char[](即 cad),因此导致类型不匹配。

Why this error occurs?

表达式 ptr[0] 的类型为 char[1] 因为 ptr 被声明为指向 char[1]

类型数组的指针
char (*ptr)[1];

表达式 cad 的类型为 char * 并且等于数组 cad.

的第一个字符的地址

来自 C 标准(6.3.2.1 左值、数组和函数指示符)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

因此在赋值语句的左边

ptr[0] = cad;

有一个 char[1] 类型的数组。在赋值的右边有一个char *类型的指针。这些类型不兼容,数组没有赋值运算符。

看来你的意思如下

#include <stdio.h>

int main(void)
{
    char cad[] = "abc";

    char * ptr[1];

    ptr[0] = cad;

    // puts( ptr[0] );

    return 0;
}