当前位置:网站首页>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;
}
边栏推荐
- Data Middle Office Construction (VII): Data Asset Management
- Game Security 03: A Simple Explanation of Buffer Overflow Attacks
- Modify Postman installation path
- 【元胞自动机】基于matlab界面聚合元胞自动机模拟【含Matlab源码 2004期】
- Handwritten binary search tree and test
- IDEA调试
- 【uniCloud】云对象的应用与提升
- 这个地图绘制工具太赞了,推荐~~
- The fledgling Xiao Li's 113th blog project notes: Wisdom cloud smart flower watering device combat (2) - basic Demo implementation
- 大佬们,MySQL cdc source在增量过程中回收 replication slave 和 r
猜你喜欢
随机推荐
Ordinary users cannot access HGFS directory
leetcode: 1562. Find latest grouping of size M [simulation + endpoint record + range merge]
手写二叉查找树及测试
[Search topic] After reading the inevitable BFS solution to the shortest path problem
Browser download shortcut to desktop (PWA)
普通用户无法访问hgfs目录
New York University et al | TM-Vec: Template Modeling Vectors for Rapid Homology Detection and Alignment
MYSQL query interception optimization analysis
RTL8762DK RTC (5)
设备树——dtb格式到struct device node结构体的转换
软考高级系统架构设计师系列之:系统开发基础知识
IDEA does not recognize the module (there is no blue square in the lower right corner of the module)
Raspberry pie arm version of GCC installed configuration and environment variables
MySQL modifies SQL statements to optimize performance
Parse the bootargs from the device tree (dtb format data)
Elastic Stack的介绍
Chain programming, packages, access
HCIP(15)
MYSQL Index Analysis
leetcode6133. 分组的最大数量(中等)