-1

我正在尝试创建一个ints 的二维矩阵并使用malloc().
我希望矩阵看起来像这样:{{-4,0},{-3,0},{-2,0},{-1,0},{1,0},{2,0},{3,0},{4,0}} 但我希望以后能够更改它,所以我尝试使用malloc(). 我创建了:

typedef int** scores_table

所以我的函数可以返回类型scores_table

这是我的代码:

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;
}

问题是 - 函数只返回-4,我不知道为什么。我究竟做错了什么?

4

2 回答 2

1

打印结果时,您可能做错了什么。这段代码:

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;
}

给出这个输出:

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

我认为这是你所期望的?

于 2014-01-03T09:15:58.163 回答
1

为什么不让数组本身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;
}
于 2014-01-03T09:08:31.007 回答