2D array via malloc with two indices and one free()?

Hi,

I just had an interview where I think a question asked of me was simply impossible, but I just wanted to double check.

Basically, I was asked to write a function that would use malloc to return an int** that could be called with two dimension sizes, the result referenced with two indices, and then could be freed with just one call to malloc.

Example of a function that would use malloc to return an int** that could be called with two dimension sizes, referenced with two indices, and then could be freed with more than one call to malloc:
1
2
3
4
5
6
7
8
9
int**alloc2DMatrix(int i,int j)
{
    int **mat=(int**)malloc(i*sizeof(int*));
    for(long index=0;index<i;index++)
        {
        mat[index]=(int*)malloc(j*sizeof(int));
        }
    return mat;
}

That would enable access with two indices like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    int** mat3x3 =alloc2DMatrix(3,3);
    for(long i=0;i<3;i++)
        {
        for(long j=0;j<3;j++)
            {
            mat3x3[i][j]=((i+1)*10+j);
            }
        }
    cerr<<"mat3x3="<<endl;
    for(long i=0;i<3;i++)
        {
        for(long j=0;j<3;j++)
            {
            cerr<<"\t"<<mat3x3[i][j];
            }
        cerr<<endl;
        }    
    for(long i=0;i<3;i++)
        {
        free(mat3x3[i]);
        }
    free(mat3x3);

However, if one want's only one call to free, I don't think it's possible to also reference with two indices. I think that could only be done with a 1D array and 1 index. It might be possible to make a function that takes two indices and a 1D array and returns the correct number, but am I wrong what was asked of me cannot be done with a 2D array? Is there a way? Basically, my understanding was that the first index points to the next byte if it isn't separately allocated to a different size. Is that right? Is there any way to do what they asked? They seemed to think there might be a way to point the pointer of the first index of a one-time-allocated 2D array to the right offsets in memory, but I cannot find any way to do that. Am I missing something?
I can get this to work, but is it reliable?
1
2
3
4
5
6
7
8
9
int**alloc2DMatrixVia1D(int i,int j)
{
    int **mat=(int**)malloc(i*sizeof(int*)+i*j*sizeof(int));
    for(long index=0;index<i;index++)
        {
        mat[index]=(int*)(mat+i+j*index);
        }
    return mat;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    int**mat=alloc2DMatrixVia1D(3,3);
    for(long i=0;i<3;i++)
        {
        for(long j=0;j<3;j++)
            {
            mat[i][j]=((i+1)*10+j);
            }
        }
    cerr<<"mat="<<endl;
    for(long i=0;i<3;i++)
        {
        for(long j=0;j<3;j++)
            {
            cerr<<"\t"<<mat[i][j];
            }
        cerr<<endl;
        }
    free(mat);
Last edited on
Topic archived. No new replies allowed.