gpt4 book ai didi

c - 指向数组的指针错误

转载 作者:行者123 更新时间:2023-12-02 09:26:49 25 4
gpt4 key购买 nike

我有这个代码

#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?

表达式 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;
}

关于c - 指向数组的指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37259108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com