简体   繁体   中英

return a fixed size array in c

I would like a function to return an array, or a pointer to an array, in either c or c++, that does something like the following:

double[][] copy(double b[][], int mx, int my, int nx, int ny)
{   
    double[nx][ny] a;
    int i,j;

    for(i = mx; i<= nx; ++i) 
         for(j = my; j<= ny; ++j) 
               a[i][j] = b[i][j];

    return a;   
}

void main(void){

    double A[2][3];
    double B[2][3] = {{1,2}{3,4}{5,6}};

    A = copy(B,0,0,1,2);        
}

This is the proper method for returning an array from a function is as follows:

#define NUM_ROWS (5)
#define NUM_COLS (3)

char **createCharArray(void)
{
    char **charArray = malloc(NUM_ROWS * sizeof(*charArray));
    for(int row = 0; row < NUM_ROWS; row++)
        charArray[row] = malloc(NUM_COLS * sizeof(**charArray));

    return charArray;
}

In this example, the above function can be called like this:

char **newCharArray = createCharArray();

newCharArray can now be used:

char ch = 'a';

for(int row = 0; row < NUM_ROWS; row++)
    for(int col = 0; col < NUM_COLS; col++)
        newCharArray[row][col] = ch++;

An array can be passed as an argument to function similarly:

void freeCharArray(char **charArr)
{
    for(int row = 0; row < NUM_ROWS; row++)
        free(charArr[row]);
    free(charArr);
}

You can return the double ** from your copy function like this.

  double ** copy(double *src, int row, int col)
  {
    // first allocate the array with required size
    double **copiedArr = (double **) malloc(sizeof(double *)*row);

    for(int i=0;i<row;i++)
    {
       // create space for the inner array
       *(copiedArr+i) = (double *) malloc(sizeof(double)*col);
       for(int j=0; j<col; j++)
       {
         // copy the values from source to destination.
         *(*(copiedArr+i)+j) = (*(src+i+j));
       }
    }

    // return the newly allocated array.
    return copiedArr;
   }

call to this function is done like this.

double src[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
double **dest = copy(&src[0][0],3,3); //here is your new array

Here you have to assign returned value of copy() to double** not to double[][] . If you try to assign the returned value to array then it will generate "Incompatible types" error ( detail ).

As memory allocated to copiedArray on the heap so you have to take responsibility to clear the memory.

void freemem(double **mem, int row)
  {
    for(int i=0;i<row; i++)
    {
      free(*(mem+i));
    }
    free(mem);
  }

I also want to point out some correction in your sample code:

  • return type of main should be int.
  • one should put the return statement at the end of main.
  • you can't return the stack allocated value, it is cause of crash in most of cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM