0

I'm doing a few experiments to solve an exercise problem from The C++ Programming Language (4th edition), Stroustrup.

Here's my code:

#include <iostream>

using std::cout;
using std::endl;

struct arr_holder {
    int mem_arr[];
};

int main()
{
    int lcl_arr[10];
    arr_holder ah;

    cout << &lcl_arr[0] << endl;
    cout << &ah.mem_arr[0] << endl;

    return 0;
}

The program prints two different addresses of lcl_arr and ah.mem_arr when compiled on my Linux g++ (4.9.2), like the following:

$ g++ foo.cc && ./a.out
0x7ebe4670
0x7ebe4698

However, when compiled on MinGW g++ (5.3.0), they're the same:

C:\sandbox>g++ foo.cc && a.exe
0x60fef8
0x60fef8

So, obviously, writing to either lcl_arr or ah.mem_arr would result in writing to the same array because they point to the same address, which I find to be quite surprising, because I think a local array (lcl_arr) and a member array (ah.mem_arr) are totally different things.

Can someone explain to me why they get the same address location on MinGW?

Rama
  • 3,222
  • 2
  • 11
  • 26
  • 2
    `a.cpp:2:17: warning: ISO C++ forbids zero-size array 'mem_arr' [-Wpedantic] int mem_arr[];` –  May 05 '17 at 17:58
  • 2
    This is not standard C++. What you are seeing is C extension: http://stackoverflow.com/questions/14643406/whats-the-need-of-array-with-zero-elements – NathanOliver May 05 '17 at 17:59
  • " because I think a local array (lcl_arr) and a member array (ah.mem_arr) are totally different things." - they are not. –  May 05 '17 at 17:59
  • The C extension you are using relies on you allocating extra memory when you create your object. You are allocating it as a local variable, no extra storage is provided for the zero-sized array. [Link](https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html). It seems to me like this would be undefined behavior. – François Andrieux May 05 '17 at 18:04
  • @NeilButterworth Sorry for the ambiguity. "Different objects" is what I meant. – Deokkee Min May 05 '17 at 18:07
  • 1
    OK, but the behaviour you are seeing is not defined by the C++ Standard, as zero-sized arrays are not part of it - so don't use them. –  May 05 '17 at 18:09
  • @NeilButterworth OK, I won't. I wrote the example code because the exercise asked me to "do a few experiments invloving [...] a local array of ints, [...] and a member array of ints." and I accidentally found this behavior. – Deokkee Min May 05 '17 at 18:20
  • @FrançoisAndrieux Thanks for the comment. – Deokkee Min May 05 '17 at 18:24

0 Answers0