指向具有不兼容行长的2D数组的指针 [英] Pointer to 2D array with incompatible row length

查看:75
本文介绍了指向具有不兼容行长的2D数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码

    char arr[5] = {'A', 'E', 'I', 'O', 'U'};
    char (*p_arr)[1] = &arr;
    printf("%c\n", p_arr[0][4]); //returns 'U'

为什么没有错误,因为

    char (*p_arr)[1] = &arr;

似乎是不兼容类型(char (*)[5]而不是必需的char (*)[1])的初始化?此外,p_arr[0][4]要求数组的第5个元素应该仅具有1元素.那不是错吗?

seems to be an initialization from an incompatible type (char (*)[5] instead of required char (*)[1])? Moreover, p_arr[0][4] asks for the 5th element of an array supposed to have only 1 element. Isn't that wrong ?

推荐答案

您的编译器损坏/配置不正确/不兼容.

Your compiler is broken/incorrectly configured/non-compliant.

指向1个元素的数组的数组指针与指向5个元素的数组的数组指针不兼容. C中的简单赋值规则说,必须是一个有效的指针赋值(C11 6.5.16.1强调我的):

An array pointer to an array with 1 element is not compatible with an array pointer to an array of 5 element. The rule of simple assignment in C says that a valid pointer assignment must be (C11 6.5.16.1 emphasis mine):

  • 左操作数具有原子,限定或不限定的指针类型,并且(考虑到左操作数在左值之后将具有的类型 转换)两个操作数都是指向合格或不合格的指针 兼容类型的版本,并且左侧指向的类型具有 右边所指类型的所有限定词;
  • the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;

如果我们从引用的文本中删除所有正式的标准术语,则会以纯英语结尾:

If we remove all the formal standard terms from the cited text, we end up with this in plain English:

=运算符的左操作数具有指针类型,并且两个操作数都是指向兼容类型的指针.

这不是您的代码中的情况,因此它包含称为约束违反的内容,这意味着该代码违反了C标准所允许的内容.

This is not the case in your code, so it contains something known as constraint violation, meaning that the code violates what's allowed by the C standard.

这篇关于指向具有不兼容行长的2D数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆