当前位置:网站首页>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;
}
边栏推荐
- 彻底关闭Chrome浏览器更新及右上角的更新提示
- 北京突然宣布,元宇宙重大消息
- STK8321 I2C (Shengjia-accelerometer) example
- second uncle
- RTL8762DK uses DebugAnalyzer (four)
- ARM 交叉编译
- 【Make YOLO Great Again】YOLOv1-v7全系列大解析(Neck篇)
- [Data analysis] Based on matlab GUI student achievement management system [including Matlab source code 1981]
- 情人节浪漫3D照片墙【附源码】
- [cellular automata] based on matlab interface aggregation cellular automata simulation [including Matlab source code 2004]
猜你喜欢
Four ways the Metaverse is changing the way humans work
Device tree - conversion from dtb format to struct device node structure
纽约大学等 | TM-Vec:用于快速同源检测和比对的模版建模向量
【搜索专题】看完必会的BFS解决最短路问题攻略
Detailed explanation of TCP protocol
IDEA修改注释字体
second uncle
Summary of JVM interview questions (continuously updated)
leetcode6133. 分组的最大数量(中等)
Browser download shortcut to desktop (PWA)
随机推荐
lua entry case combat 123DIY
Open source project site must-have & communication area function
HIRO: Hierarchical Reinforcement Learning 】 【 Data - Efficient Hierarchical Reinforcement Learning
SC7A20 (Silan Micro-Accelerometer) Example
北京突然宣布,元宇宙重大消息
New York University et al | TM-Vec: Template Modeling Vectors for Rapid Homology Detection and Alignment
device node结构体转换成platform_device结构体
带你体验一次类型编程实践
[Message Notification] How about using the official account template message?
STK8321 I2C (Shengjia-accelerometer) example
Flink 部署和提交job
Parse the bootargs from the device tree (dtb format data)
Basic usage concepts of vim
2022 CSP-J1 CSP-S1 Round 1 Preliminary Competition Registration Guide
[uniCloud] Application and Improvement of Cloud Objects
IDEA debugging
[SemiDrive source code analysis] series article link summary (full)
Introduction to machine learning how to?
初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现
被 CSDN,伤透了心