当前位置:网站首页>Unknown Bounded Array
Unknown Bounded Array
2022-08-01 03:17:00 【programming snippet】
有两个文件,A file is a declaration of an array,The other is the definition of the array.If the definition of the array changes,For example, it has become contained5个元素的数组,Then the associated statement must also be changed.Once there are more files, some files will be forgotten to be modified,Unexpected problems will occur.
int array[4] = {
1, 2, 3, 4 };
#include<iostream>
extern int array[4];
int main()
{
……
return 0;
}
Some people come up with a solution,declared as a pointer.Because arrays are implicitly type converted to pointers,But this workaround gives a segfault(如果对arrayPointer dereference words),Let's look at the program first,By the way, the address of each element is printed out:
#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;
}

很显然,Only the first address matchesC++The address form of the language.那么为什么会出现这种问题呢?
First of all this is not a compile error,Because each file is compiled separately without any problem;Second is not a link problem(Types are a compiler concept,There is no type in the link,只有符号),array符号一致;So it is a runtime error.因为指针是64位的,So it will treat the first two elements of the array as pointers(due to endianness),Directly translated addresses are invalid,So dereferencing will segfault.

正确的做法是使用Unknown Bounded Array(C++The specialized term is called incomplete class):
#include<iostream>
int array[4] = {
1, 2, 3, 4 };
void func()
{
std::cout << array << std::endl;
}
#include<iostream>
void func();
extern int array[];//Statements can be written like this,But definitions can't
int main()
{
func();
std::cout << array << std::endl;
return 0;
}
边栏推荐
- 【消息通知】用公众号模板消息怎么样?
- MYSQL-Batch insert data
- 更换树莓派内核
- IDEA调试
- 纽约大学等 | TM-Vec:用于快速同源检测和比对的模版建模向量
- Four implementations of
batch insert: have you really got it? - 黑客到底可以厉害到什么程度?
- [SemiDrive source code analysis] series article link summary (full)
- 初出茅庐的小李第114篇博客项目笔记之机智云智能浇花器实战(3)-基础Demo实现
- Basic Theoretical Knowledge of Software Testing - Use Cases
猜你喜欢
随机推荐
HCIP(15)
IDEA无法识别module(module右下角没有蓝色小方块)
MYSQL Keyword Explain Analysis
TypeScript简化运行之ts-node
这个地图绘制工具太赞了,推荐~~
Basic use of vim - command mode
纽约大学等 | TM-Vec:用于快速同源检测和比对的模版建模向量
MYSQL two-phase commit
IDEA debugging
Unknown Bounded Array
初出茅庐的小李第114篇博客项目笔记之机智云智能浇花器实战(3)-基础Demo实现
MYSQL transactions
Introduction to Oracle
Google Earth Engine - Error resolution of Error: Image.clipToBoundsAndScale, argument 'input': Invalid type
The bigger and bigger the project is, I split it like this
每周小结(*67):为什么不敢发表观点
从设备树(dtb格式数据)中解析出bootargs
C string array reverse
一个service层需要调用另两个service层获取数据,并组装成最后的数据,数据都是list,缓存如何设计?
787. 归并排序








