当前位置:网站首页>Unknown Bounded Array
Unknown Bounded Array
2022-08-01 03:02:00 【编程小段】
有两个文件,一个文件是数组的声明,另一个是数组的定义。如果数组的定义发生变化,比如说变成了含有5个元素的数组,那么相关联的声明也必须改变。一旦文件变多则会有部分文件忘记修改,就会发生意想不到的问题。
int array[4] = {
1, 2, 3, 4 };
#include<iostream>
extern int array[4];
int main()
{
……
return 0;
}
有的人想出一种解决办法,声明成指针。因为数组会隐式类型转换为指针,但这种解决方法会出现一个段错误(如果对array指针解引用的话),我们先看程序,顺便把各元素的地址打印出来:
#include<iostream>
int array[4] = {
1, 2, 3, 4 };
void func()
{
std::cout << array << std::endl;
}
#include<iostream>
void func();
extern int* array;
int main()
{
func();
//std::cout << array[1] << std::endl;
std::cout << array << std::endl;
return 0;
}

很显然,第一个地址才符合C++语言的地址形式。那么为什么会出现这种问题呢?
首先这个不是编译错误,因为各文件单独编译都没有问题;其次也不是链接问题(类型是在编译器的概念,链接中是没有类型的,只有符号),array符号一致;因此它是一个运行错误。因为指针是64位的,所以它会把数组的前两个元素看成指针(由于大小端原因),而直接转换的地址是无效的,所以解引用会发生段错误。

正确的做法是使用Unknown Bounded Array(C++专门的术语叫不完整类):
#include<iostream>
int array[4] = {
1, 2, 3, 4 };
void func()
{
std::cout << array << std::endl;
}
#include<iostream>
void func();
extern int array[];//声明可以这样写,但定义不能
int main()
{
func();
std::cout << array << std::endl;
return 0;
}
边栏推荐
猜你喜欢

HCIP(14)

JS new fun(); 类与实例 JS基于对象语言 只能通过书写构造函数充当类

How to download the Keil package

Summary of MVCC

【消息通知】用公众号模板消息怎么样?
![[Message Notification] How about using the official account template message?](/img/4d/5b47722d1f5ec1cae73fc8d930a35d.jpg)
[Message Notification] How about using the official account template message?

MYSQL-Batch insert data

IDEA does not recognize the module (there is no blue square in the lower right corner of the module)
![leetcode: 1562. Find latest grouping of size M [simulation + endpoint record + range merge]](/img/72/f52b5d3dcdb271f096c3e5108f0042.png)
leetcode: 1562. Find latest grouping of size M [simulation + endpoint record + range merge]

MYSQL Keyword Explain Analysis
随机推荐
STK8321 I2C (Shengjia-accelerometer) example
The IDEA can't find or unable to load The main class or Module "*" must not contain The source root "*" The root already belongs to The Module "*"
785. Quick Sort
"Youth Pie 2": The new boyfriend stepped on two boats, and the relationship between Lin Miaomiao and Qian Sanyi warmed up
IDEA does not recognize the module (there is no blue square in the lower right corner of the module)
解决IDEA默认情况下新建文件时,右击,new,没有XML文件的问题
pdb药物综合数据库
手写二叉查找树及测试
二舅
[SemiDrive source code analysis] series article link summary (full)
Introduction to machine learning how to?
WebApi hits an Attribute to handle exceptions uniformly
Talking about hardware device computing storage and data interaction
lua entry case combat 123DIY
device node结构体转换成platform_device结构体
RTL8762DK UART (two)
Guys, MySQL cdc source recycles replication slave and r in incremental process
Take you to experience a type programming practice
Compiled on unbutu with wiringPi library and run on Raspberry Pi
【 Make YOLO Great Again 】 YOLOv1 v7 full range with large parsing (Neck)