Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic bidimensional array

Tags:

c

I want to create a bidimensional array like so:

void **mdeclaraMatrice(int nrLini,int nrColoane, int sizeOfElement)
{
    int i;
    void **m = malloc(nrLini * 4);
    if(m==NULL)
        return NULL;
    for(i=0; i<nrLini; i++)
    {
        *(m + (i*4)) = malloc(nrColoane * sizeOfElement);
        if(*(m + (i*4)) == NULL)
             return NULL;
    }
    return m;
}

I whant to use it like this:

int **m = (int **)mdeclaraMatrice(n,m,sizeof(int));

but it doesn't work. What do I do wrong?

like image 641
Tandura Avatar asked Nov 30 '14 14:11

Tandura


1 Answers

You should use m[i] instead of *(m+i*4) and let the compiler do the arithmetic.

In addition, you should deallocate the already-allocated memory in case of a failure.

Try this instead:

void **mdeclaraMatrice(int nrLini, int nrColoane, int sizeOfElement)
{
    int i;
    void **m = malloc(nrLini * sizeof(void*));
    if (m == NULL)
        return NULL;
    for (i=0; i<nrLini; i++)
    {
        m[i] = malloc(nrColoane * sizeOfElement);
        if (m[i] == NULL)
        {
             while (i-- > 0)
                 free(m[i]);
             free(m);
             return NULL;
        }
    }
    return m;
}
like image 92
barak manos Avatar answered Oct 15 '22 04:10

barak manos