C++ 中这些外部声明有什么区别?
让我们拥有包含以下内容的文件:
file1.cpp
: double array[100];
file2.cpp
(file1 的客户端.cpp
):
/// What the difference between this:
extern double* array;
/// and this?
extern double array[];
如果我使用以第一种方式声明的数组,我会收到段错误。如果是第二个,则工作正常。这让我很困惑,因为在常规的 C++ 程序中,我可以轻松地执行以下操作,并且这些对象将是相等的:
double array[100];
double* same_array = array;
/// array[0] is equal to same_array[0] here
/// But why they are not equal in the example with extern?
Lets have the files with the following contents:
file1.cpp
: double array[100];
file2.cpp
(client of file1.cpp
):
/// What the difference between this:
extern double* array;
/// and this?
extern double array[];
If I use array declared in the first way I receive segfault. If second, it works ok. It confuses me, since in a regular C++ programm I can easily do the following and these objects would be equal:
double array[100];
double* same_array = array;
/// array[0] is equal to same_array[0] here
/// But why they are not equal in the example with extern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不同之处在于,第一个是指向 double 类型的指针
第二个是双精度数组。
这里需要注意的重要一点是:
数组不是指针!
只要数组类型不合法,但指针类型合法,具有数组类型(可以是数组名称)的表达式就会转换为指针。
根据提到的规则,上面的数组名称衰减为指向其第一个元素的指针。
为什么你的程序崩溃了?
数组声明创建一个数组,该数组根据存储类(声明的位置)占用一些内存。
而指针只是创建一个指向某个地址的指针。您将明确需要使其指向某个有效对象才能使用它。
这应该是一本很好的读物:
如何在 C++ 中使用数组?
The difference is that first is an pointer to the type double
and second is an array of double.
Important thing to note here is:
Arrays are not Pointers!
An expression with array type (which could be an array name) will convert to a pointer anytime an array type is not legal, but a pointer type is.
As per the rule mentioned,In above the array name decays in to a pointer to its first element.
Why does your program crash?
An array declaration creates an array which occupies some memory depending on the storage class(where is declared).
While a pointer just creates an pointer which points to some address. You would explicitly need to made it point to some valid object to be able to use it.
This should be a good read:
How do I use arrays in C++?
当您现在执行
array[i]
时,在某些地方array
实际上定义为数组(而不是像上面那样定义为指针) ,然后它会尝试将数组的内容解释为地址。例如,在另一个文件/另一个翻译单元中,我们定义为让我们假设
0.0
所有位都为零。然后,上面的extern double*
上的array[1]
操作将尝试取消引用所有位都为零的指针地址。在大多数盒子上,这都会崩溃。而对于其余的其他人来说,这会导致随机的废话。When you now do
array[i]
, and at some placearray
is actually defined as an array (instead of as a pointer like above), then it will try to interpret the contents of the array as an address. So for example in another file/another translation unit we defined at asLet's assume that
0.0
has all bits zero. Then thearray[1]
operation on theextern double*
above would try to dereference a pointer address having all bits zero. On most boxes, that will crash. And on the remaining others it would result in random nonsense.