Dynamic matrix allocation - allocating a contiguous block of ints using malloc not working

211 views Asked by At

I'm trying to create a 2D matrix of ints and allocate memory to the same using malloc().
I want the matrix to look like this: {{-4,0},{-3,0},{-2,0},{-1,0},{1,0},{2,0},{3,0},{4,0}} But I want to be able to change it later, so I'm trying to dynamically allocate a contiguous block using malloc(). I've created :

typedef int** scores_table

so my function can return the type scores_table.

This is my code:

scores_table alloc_scores_table(){
    scores_table scores;
    int i,j, *row;
    row=(int*)malloc(sizeof(int)*2*8);
    scores=(scores_table)malloc(sizeof(int*)*8);
    if(scores==NULL || row==NULL){
        quit();
    }
    for(i=0;i<8;i++){
        scores[i]=row+i*2;
    }
    for(i=0;i<8;i++){
        for(j=0;j<2;j++){
            if(j==1){
                scores[i][j]=0;
            }
            else{
                if(i>3){
                    scores[i][j]=-4+1+i;
                }
                else{
                    scores[i][j]=-4+i;
                }
            }
        }
    }
    return scores;
}

The problem is - the function is returning only -4 and I have no idea why. What am I doing wrong?

2

There are 2 answers

0
legends2k On

Why not have the array itself malloc'd?

typedef int scores_table[2][8];

scores_table* alloc_scores_table()
{
    scores_table *scores = malloc(sizeof *scores);
    if(scores)
    {
        // your initalization code here
        size_t i, j;
        for(i = 0; i < 8; i++) {
            for(j = 0; j < 2; j++) {
                if(j == 1) {
                    *scores[i][j]=0;
                }
                else {
                    if(i > 3) {
                        *scores[i][j]=-4+1+i;
                    }
                    else {
                        *scores[i][j]=-4+i;
                    }
                }
            }
        }
    }

    return scores;
}
2
Thomas Padron-McCarthy On

You are probably doing something wrong when you print the result. This code:

int main(void) {
    scores_table st = alloc_scores_table();

    for (int i = 0; i < 8; ++i) {
        for (int j = 0; j < 2; ++j) {
            printf("st[%d][%d] = %d\n", i, j, st[i][j]);
        }
    }

    return 0;
}

gives this output:

st[0][0] = -4
st[0][1] = 0
st[1][0] = -3
st[1][1] = 0
st[2][0] = -2
st[2][1] = 0
st[3][0] = -1
st[3][1] = 0
st[4][0] = 1
st[4][1] = 0
st[5][0] = 2
st[5][1] = 0
st[6][0] = 3
st[6][1] = 0
st[7][0] = 4
st[7][1] = 0

which I think is what you expected?