Hi Members,
I'm new to 2D pointers, and C. I'm trying few basic things, of creating new pointer, printing, adding matrices.
Below is my code:
Code:
int main(){
int (*add)[3]=malloc(3*3*sizeof(int));
int i=0,j=0;
int mat1[3][3]={{2,3,70},{20,-8,90},{40,-2,-1}};
int mat2[3][3]={{8,17,-30},{80,12,-10},{-20,-8,100}};
printf("Initialized 2 matrices\n");
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
*(*(add+i)+j) = mat1[i][j]+mat2[i][j];
}
}
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
printf("%d\t",*(*(add+i)+j));
}
printf("\n");
}
return 0;
}
I get the desired output from this, if I keep:
int (*add)[3]=malloc(3*3*sizeof(int));
If I use:
int *add=malloc(3*3*sizeof(int));
I get error as:
matrix_add.c:14: error: invalid type argument of ‘unary *’ (have ‘int’)
Why is so?
with *add=malloc(3*3*sizeof(int)); do I not get a pointer in contiguous memory?
(*add)[3]=malloc(3*3*sizeof(int)); this is same as creating a 2D pointer.
Please enlighten.