-1

I have a few straightforward questions:-

  1. Is the following correct according to a normal c++ compiler?

    int arr[3][4];
    void func(int *a, int m, int n)
    {
     int i,j;
     cin>>i>>j; 
     cout<< a[i*n + j]; //is this way of addressing correct provided 0<=i<m and 0<=j<n
    } 
    
    int main()
    {
     func((int*)arr, 3,4);
    }
    
  2. If the bounds of an array strictly has to be a constant expression, why doesn't the following generate compiler errors?

    int func(int m, int n)
    {
     int arr[m][n]; //m and n are not known until run time
    }
    
AvinashK
  • 3,309
  • 8
  • 43
  • 94
  • Under a strict reading of the Standard it's generally not possible to use a multidimensional array as if it were a flat array (beyond the first few elements). This is something that is routinely ignored however, to the extent that I didn't really find any SO answer that mentions it -- other than [one](http://stackoverflow.com/a/7273599/726300) by yours truly. – Luc Danton Sep 09 '12 at 09:50

2 Answers2

2

Is the following correct according to a normal c++ compiler?

Yes, because the Standard specifies that even arrays with more than 1 dimensions are contigous in memory. BUT! You're misunderstanding array indexing and length a bit - i and j have to be strictly less than 3 and 4, respectively. The 3 and 4 are the sizes of the array in its two dimensions, and not the maximal possible subscripts.

If the bounds of an array strictly has to be a constant expression, why doesn't the following generate compiler errors?

Maybe you're using a compiler that supports this as an extension (think of GCC, Clang, etc.)

1

It's actually undefined behavior as you access the array a using uninitialized values of i and j. Otherwise, if you are using calculating the array index correctly (within the bounds), then it's valid.

You might be using gcc extension for variable length array in your case.

P.P
  • 117,907
  • 20
  • 175
  • 238