From: jklowden@speakeasy.net   
      
   On Sun, 24 Mar 2013 16:21:33 CST   
   Robert Upton wrote:   
      
   > I am in the process of learning c++ and want to pass a 2D array to a   
   > function.   
      
   The compiler complains because you have an array of   
      
    int[5][5]   
      
   that you're passing to a function whose parameter is declared as   
      
    int *   
      
   Think about this question: given only a pointer, how is the compiler   
   to know which element is intended by xp[1][1]?   
      
   I rewrote your code below so that it compiles (and probably does what   
   you want), and is a little more idiomatic. I won't belabor the style   
   changes. Two points regarding your question:   
      
   1. AFAIK C++ requires compile-time constants for array dimensions.   
   Some compilers will do what you mean but enum is a better choice than   
   static initialization of a variable.   
      
   2. The type int[][nsamp] defines a "pointer to an array of 5   
   integers". As i varies, it "moves by fives". This lets you do things   
   like   
      
    int *pi = xp[1];   
      
   because xp was an array (now degraded to pointer) whose elements are   
   array-of-5-integers. So, xp[1] is an array of (five) integers and,   
   like any array, we can assign its location to a pointer.   
      
   In practice, this form is seldom used, for two reasons. One,   
   std::vector is generally a better choice. Two, because the dimensions   
   are often not known at compile time, low-level code like this normally   
   uses *int and dereferences i,j with something like   
       
    int a = *(xp + i * nsamp + j);   
      
   or, equivalently   
      
    int a = xp[i * nsamp +j];   
      
   HTH.   
      
   --jkl   
      
      
   /*   
    * code   
    */   
   enum { nsamp = 5 };   
      
   void   
   doubleDimArray(int xp[][nsamp], int nsamp)   
   {   
    for(int i = 0; i < nsamp; ++i) {   
    for (int j = 0; j < nsamp; ++j) {   
    xp[i][j] = j - (nsamp-1)/2;   
    }   
    }   
   }   
      
   int   
   main(int argc, char** argv) {   
    int xxarray[nsamp][nsamp];   
    doubleDimArray(xxarray,nsamp);   
    return 0;   
   }   
      
      
   --   
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
    [ comp.lang.c++.moderated. First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|