Question about dynamic memory allocation (in C)

Consider the following codes:

#include <stdio.h>
#include <malloc.h>

void allocateMatrix(int **m, int l, int c)
{
    int i;

    m = (int**) malloc( sizeof(int*) * l );
    for(i = 0; i < l; i++)
        m[i] = (int*) malloc( sizeof(int) * c );
}

int main()
{
    int **m;
    int l = 10, c = 10;
    allocateMatrix(m, l, c);
    m[0][0] = 9;
    printf("%d", m[0][0]);

    return 0;
}

The code above generates a memory allocation error and fails.

But the code below will work correctly, the question is: WHY?

#include <stdio.h>
#include <malloc.h>

int** allocateMatrix(int l, int c)
{
    int i;

    int **m = (int**) malloc( sizeof(int*) * l );
    for(i = 0; i < l; i++)
        m[i] = (int*) malloc( sizeof(int) * c );
    return m;
}

int main()
{
    int **m;
    int l = 10, c = 10;
    m = allocateMatrix(l, c);
    m[0][0] = 9;
    printf("%d", m[0][0]);

    return 0;
}

I don’t understand why the first code crashes, since I just pass a pointer to the m pointer (a variable that contains the memory address of the first matrix memory) as an argument. I do not see the difference between the codes (in practice). I would appreciate any clear explanation.

Thanks, Rafael Andrita

+3
source share
4 answers

In the first example, you are not initializing m. You just change your copy. So, in other words, the caller will not see what you have done with m.

. .

, (, ):

void allocateMatrix(int ***m, int l, int c)
{
    int i;

    *m = malloc( sizeof(int*) * l );
    for(i = 0; i < l; i++)
        (*m)[i] = malloc( sizeof(int) * c );
}


/* ... */

allocateMatrix(&m, l, c);

, . , C FAQ .

+7

allocateMatrix m, , . , m , , .

+1

, , :

void allocateMatrix(int **m, int l, int c);

. , , , . , . , , m .

, , :

void allocateMatrix(int ***m, int l, int c)
{
    int i;
    *m = (int**) malloc( sizeof(int*) * l );
    for(i = 0; i < l; i++)
        (*m)[i] = (int*) malloc( sizeof(int) * c );
}

&m.

C, , , malloc, ++. . .

+1

Because in the first example, the variable m (basically) does not change. To change it, you must pass it as a reference (in C ++) or a pointer (in plain C).

0
source

All Articles