Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning a two dimensional array from a function in c++ [duplicate]

I want to use a two dimensional int array which is returned from a function how should I define the function return value ? I used int** but the compiler gave error:

int**  tableCreator(){
    int** table=new int[10][10];
    for(int xxx=1;xxx<10;xxx++){
        for(int yyy=1;yyy<10;yyy++){
            table[xxx][yyy]=xxx*yyy;
        }
    }
    return(table);  //Here:cannot convert from 'int (*)[10]' to 'int **'
}
like image 648
Mohammadreza Heydarian Avatar asked May 09 '26 21:05

Mohammadreza Heydarian


1 Answers

Try this:

#include <cstdio>
#include <cstdlib>


int** createTable(int rows, int columns){
    int** table = new int*[rows];
    for(int i = 0; i < rows; i++) {
        table[i] = new int[columns]; 
        for(int j = 0; j < columns; j++){ table[i][j] = (i+j); }// sample set value;    
    }
    return table;
}
void freeTable(int** table, int rows){
    if(table){
        for(int i = 0; i < rows; i++){ if(table[i]){ delete[] table[i]; } }
        delete[] table;    
    }
}
void printTable(int** table, int rows, int columns){
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < columns; j++){
            printf("(%d,%d) -> %d\n", i, j, table[i][j]);
        }    
    }
}
int main(int argc, char** argv){
    int** table = createTable(10, 10);
    printTable(table, 10, 10);
    freeTable(table, 10);
    return 0;
}

You need the second loop to allocate a 2-d array in C and similar operation to free it. a two-D array is in essence an array of arrays so can be expressed as a pointer array. the loop initializes the arrays pointed to the pointers.

Clarifying as per conversation with @Eric Postpischil below: changed createTable to take row/column count for truly dynamic allocation.

like image 122
mohaps Avatar answered May 11 '26 12:05

mohaps