Dummy commit to test new ssh key
[eleutheria.git] / homework / 2darray.c
blob02b3ee4800644cf5f31130ad40dac6b61bef7921
1 #include <stdio.h>
2 #include <stdlib.h>
4 /* Incorrect */
5 void foo1(int **mat, int rows, int cols)
7 int i, j;
9 for (i = 0; i < rows; i++) {
10 for (j = 0; j < cols; j++)
11 printf("%d ", mat[i][j]);
12 printf("\n");
16 /* Correct */
17 void foo2(int **mat, int rows, int cols)
19 int i, j;
20 int **aux;
22 aux = malloc(rows * sizeof(int *));
23 if (aux == NULL) {
24 perror("malloc");
25 exit(EXIT_FAILURE);
28 for (i = 0; i < rows; i++) {
29 aux[i] = (int *)mat + cols * i;
30 for (j = 0; j < cols; j++)
31 printf("%d ", aux[i][j]);
32 printf("\n");
35 free(aux);
38 /* Correct */
39 void foo3(int **mat, int rows, int cols)
41 int i, j;
43 for (i = 0; i < rows; i++) {
44 for (j = 0; j < cols; j++)
45 printf("%d ", *((int *)mat + cols * i) + j);
46 printf("\n");
50 int main(void)
52 int mat[4][3] = { { 1, 2, 3},
53 { 4, 5, 6},
54 { 7, 8, 9},
55 {10, 11, 12} };
57 foo3((int **)&mat[0][0], 4, 3);
58 foo2((int **)&mat[0][0], 4, 3);
59 /* foo1((int **)&mat[0][0], 4, 3); */
61 return EXIT_SUCCESS;