我正在尝试创建一个 int
的二维矩阵,并使用 malloc()
为其分配内存。
我希望矩阵看起来像这样:{{-4,0},{-3,0},{-2,0},{-1,0},{1,0},{2, 0},{3,0},{4,0}}
但我希望稍后能够更改它,因此我尝试使用 malloc()
动态分配连续 block 。
我创建了:
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
,我不知道为什么。
我究竟做错了什么?
最佳答案
当你打印结果时,你可能做错了什么。这段代码:
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
我认为这是您所期望的?
关于c - 动态矩阵分配 - 使用 malloc 分配连续的整数 block 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20899872/