arrays/array-allok.c - Et program der dynamisk allokerer et to-dimensionelt array. | Lektion 9 - slide 27 : 30 Program 5 |
#include <stdio.h> #include <stdlib.h> #define N 4 #define M 6 int main(void) { int *pint, i, j; // Allocate space for a N x M matrix: pint = (int *)malloc(N*M*sizeof(int)); if (pint == NULL){ printf("Cannot allocate enough memory. Bye"); exit(EXIT_FAILURE); } // Initialize the matrix: for (i=0; i<N; i++) for (j=0; j<M; j++) *(pint + M*i + j) = (i+1) * (j+1); // Print the matrix nicely: for (i = 0; i < M * N; i++){ printf("%4i ", *(pint + i)); if ((i+1) % M == 0) printf("\n"); } // Free the space: free(pint); return 0; }