简体   繁体   English

这些C ++中的extern声明有什么区别?

[英]What is the difference between these extern declarations in C++?

Lets have the files with the following contents: 让我们拥有以下内容的文件:

file1.cpp : double array[100]; file1.cppdouble array[100]; file1.cpp double array[100];

file2.cpp (client of file1.cpp ): file2.cpp (客户端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. 如果我使用以第一种方式声明的数组,则会收到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: 这使我感到困惑,因为在常规的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?

The difference is that first is an pointer to the type double 区别在于,第一个是指向double类型的指针
and second is an array of double. 第二个是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. 只要数组类型不合法但指针类型合法,带有数组类型(可能是数组名称)的表达式都将转换为指针。

double array[100];
double* same_array = array;

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++? 如何在C ++中使用数组?

extern double* array;

When you now do array[i] , and at some place array 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. 现在,当您执行array[i]并在某个地方将array实际定义为数组(而不是像上面的指针一样)时,它将尝试将数组的内容解释为地址。 So for example in another file/another translation unit we defined at as 因此,例如,在我们定义为的另一个文件/另一个翻译单元中

double array[1] = { 0.0 };

Let's assume that 0.0 has all bits zero. 假设0.0所有位为零。 Then the array[1] operation on the extern double* above would try to dereference a pointer address having all bits zero. 然后,对上述extern double*array[1]操作将尝试取消对所有位为零的指针地址的引用。 On most boxes, that will crash. 在大多数盒子上,这会崩溃。 And on the remaining others it would result in random nonsense. 而其他的将导致随机的废话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM