Thread: dynamic multidimensional arrays as function arguments

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    1

    Post dynamic multidimensional arrays as function arguments

    I have the following array:

    Code:
    double **A;
    
    A = new double*[s];
        for (int i=0;i<s;i++)
          A[i]=new double[3];
    I want to pass the array to the following function:

    Code:
    function1 (double A[][3],int n)
    {
    ...
    }
    but I get the message from the g++ compiler:
    cannot convert `double**' to `double (*)[3]' for argument
    `1' to `double function1(double (*)[3], int)'

    How should I declare and initialize the dynamic array
    to make it work with the function? I cannot change
    function1, because it is written by someone else.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Perhaps like this?
    Code:
    #include <iostream>
    
    void function1 (double A[][3], int n)
    {
       int k = 0;
       for ( int i = 0; i < n; ++i )
       {
          for ( int j = 0; j < 3; ++j )
          {
             A[i][j] = ++k;
          }
       }
    }
    
    int main(void)
    {
       const int size = 5;
       double (*array)[3] = new double [size][3];
       function1(array, size);
       for ( int i = 0; i < size; ++i )
       {
          for ( int j = 0; j < 3; ++j )
          {
             std::cout << "array[" << i << "][" << j << "] = " << array[i][j] << '\n';
          }
       }
       delete[] array;
       return 0;
    }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating and freeing dynamic arrays
    By circuitbreaker in forum C++ Programming
    Replies: 8
    Last Post: 02-18-2008, 11:18 AM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  4. Replies: 10
    Last Post: 09-27-2005, 12:49 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM