0

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?
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
bananov
  • 163
  • 1
  • 5

2 Answers2

2

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.

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++?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • I really cannot understand why, so that's why I wrote a codesnippet where are the same and could be treated in the same way. – bananov Dec 18 '11 at 14:48
  • Yes, sometimes arrays can act like or be treated like pointers. But that doesn't make them equivalent. You'll just run into problems if you refuse to learn the difference and use them appropriately. – Cody Gray - on strike Dec 18 '11 at 14:49
  • Array are not Pointers, but ``same_array[10]'' is a valid statement, why? Because it is a syntax sugar? – bananov Dec 18 '11 at 14:50
2
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. 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. Then the array[1] operation on the extern 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.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212