I'm trying to create a 2D matrix of int
s 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?
Why not have the array itself
malloc
'd?