When I test your code, I get these errors and warnings.
/home/dac/ClionProjects/gnu/main.c: In function ‘main’:
/home/dac/ClionProjects/gnu/main.c:11:9: warning: passing argument 1 of ‘print’ from incompatible pointer type [-Wincompatible-pointer-types]
print(a,3,3);
^
/home/dac/ClionProjects/gnu/main.c:3:6: note: expected ‘int **’ but argument is of type ‘int (*)[3]’
void print(int **,int,int);
^
/home/dac/ClionProjects/gnu/main.c: In function ‘print’:
/home/dac/ClionProjects/gnu/main.c:21:35: error: expected ‘)’ before ‘;’ token
printf("%d ",*((A+i*n12)+j);
^
/home/dac/ClionProjects/gnu/main.c:21:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d ",*((A+i*n12)+j);
^
/home/dac/ClionProjects/gnu/main.c:22:5: error: expected ‘;’ before ‘}’ token
}
^
If you just want to print a matrix, you can use the matrix you created and redeclare how you print it, similar to the following code.
#include <stdio.h>
#define size 3
void print_matrix(int x, int y, int a[size][size]) {
int i, j;
for(i = 0; i < x; i++) {
for(j = 0; j < y; j++)
printf("%d\t", a[i][j]);
putchar('\n');
}
}
int main() {
int a[size][size]={
{1,0,1},{1,1,1}, {1,1,1}
};
print_matrix(size,size, a);
return 0;
}
Output
/system/cmake/generated/gnu-fadf49ce/fadf49ce/Debug/gnu
1 0 1
1 1 1
1 1 1
Process finished with exit code 0
If you want to learn about double-pointers, try using and manipulating the argv
of your program - it is already a double-pointer. Or create new matrices dynamically: int **matrix = malloc(size * sizeof(int *));
Or if you want to use the pointer version of your original problem (printing a matrix using pointers).
#include <stdio.h>
#define size 3
void print_matrix(int (*a)[size], int n) {
int i, j;
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++)
printf("%d\t", a[i][j]);
putchar('\n');
}
}
int main() {
int a[][size]={
{1,0,1},{1,1,1}, {1,1,1}
};
print_matrix(a, size);
return 0;
}
The above code uses pointers and prints the same matrix:
1 0 1
1 1 1
1 1 1
To learn pointers, you can declare a matrix of pointers and try to manipulate it, the following creates and prints a matrix of random numbers using pointers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define size 3
void print_matrix(int ***matrix) {
for (unsigned row = 0; row < size; row++) {
for (unsigned column = 0; column < size; column++) {
printf("%d ", matrix[row][column]);
}
printf("\n");
}
}
int main() {
int ***matrix = malloc(size * sizeof(int **));
if (!matrix) abort();
srand(time(NULL));
for (unsigned row = 0; row < size; row++) {
matrix[row] = calloc(size, sizeof(int *));
if (!matrix[row]) abort();
for (unsigned column = 0; column < size; column++) {
matrix[row][column] = rand();
}
}
print_matrix(matrix);
return 0;
}
Output
2058554958 959327445 396140031
214331704 706399125 124749117
1280566165 206604059 668072276