加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 指向数组声明的指针

发布时间:2020-12-16 07:09:48 所属栏目:百科 来源:网络整理
导读:考虑以下情况: 1. extern int *a;int *a = new int(1); //OK 2. extern int a[];int a[5]; //Ok 3. extern int (*a)[];int (*a)[5]; //error: redefinition of 'a' with a different type: 'int (*)[5]' vs 'int (*)[]' 你能解释为什么第三种情况会抛出编译
考虑以下情况:

1.

extern int *a;
int *a = new int(1); //OK

2.

extern int a[];
int a[5]; //Ok

3.

extern int (*a)[];
int (*a)[5]; //error: redefinition of 'a' with a different type: 'int (*)[5]' vs 'int (*)[]'

你能解释为什么第三种情况会抛出编译时错误吗?前两次究竟是什么?我正在寻找相应的标准参考.

解决方法

简而言之:
第三种情况是不同的,因为,指针变量的类型不匹配 – extern声明指向具有未知大小(不完整类型)的int数组的指针,并且定义是针对相同的变量,但是作为指向数组的指针5个整数,根据标准是不同(有效)类型.

详细:

第一种情况是明确的:
extern int * a只声明存在int *类型的变量.
第二行定义相同的变量.

第二种情况:
?我再次阅读标准,这就是它所说的:

The declared type of an array object might be an array of unknown size
and therefore be incomplete at one point in a translation unit and
complete later on; the array types at those two points (“array of
unknown bound of T” and “array of N T”) are different types

我相信这意味着带有下标的数组的定义将变量的先前声明完成为具有未知大小(无下标)的数组 – 这就是场景2中发生的情况.

第三种情况:
使用与标准相同的含义,这两个点的数组类型具有不同的类型.
因此情况3失败,因为第一个和第二个声明将声明相同的指针变量作为指向不同类型的指针,导致“重新定义不同类型”错误

[重读标准后编辑回答]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读