c++compiler-errors

arrays declaration and addressing


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
    }
    

Solution

  • 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.)