dumb_ass_questions
dumb_ass_questions

Reputation: 85

Creating Matrix with triple pointer causes Segmentation Fault

I need to implement a matrix_create function that receives a triple pointer.
It compiles well, but when I run it I get the Segmentation Fault error, probably because I messed up somewhere in the memory allocation.
But I cannot find my mistake.

The code

#include <stdio.h>
#include <stdlib.h>

int matrix_create(int ***m, int ze, int sp);
void matrix_init(int **m, int ze, int sp);

int main (void)
{
    int ze = 3;
    int sp = 3;
    int i,j;
    int ***m = malloc(sizeof(int**));
    *m = malloc(ze * sizeof(int*));

    matrix_create(m, ze, sp);
    matrix_init(*m, ze, sp);
    for(i = 0; i < ze; ++i) {
        for(j = 0; j < sp; ++j)
            printf("%i\n", *m[i][j]);
    }
    return 0;
}

int matrix_create(int ***m, int ze, int sp)
{
    int i, k;
    if (!*m)
        return 0;
    for (i = 0; i < ze; ++i) {
        *m[i] = malloc(sp * sizeof(int));
        if (!*m[i]) {
            for (k = 0; k < i; ++k)
                free(*m[k]);
            free(*m);
            return 0;
        }
    }
    return 1;
}

void matrix_init(int **m, int ze, int sp)
{
    int i,j;
    for(i = 0; i < ze; ++i) {
        for(j = 0; j < sp; ++j)
            m[i][j] = rand() % 1000;
    }
}

Upvotes: 0

Views: 230

Answers (1)

Rabbid76
Rabbid76

Reputation: 210978

The index operator [] takes precedence over the indirection operator *.
See C Operator Precedence.

This means you have to change

*m[i]

to

(*m)[i]

in the function matrix_create:

(*m)[i] = malloc(sp * sizeof(int));
if (!(*m)[i]) {
    .....
}

and in the main program:

printf("%i\n", (*m)[i][j]);

Upvotes: 2

Related Questions