Advertisement
obernardovieira

How about 3D array (Matrix vs Malloc)

Dec 30th, 2015
386
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. //after last post I just asked myself "how about a 3D array, I have never done something like this"
  2. //Challenge accepted
  3. //And I'm surprised now
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. //for variable m, you need to know the number os columns and height!
  9. void testOne(int m[][2][5], int r, int c, int h) {
  10.     int x, y, z, a = 0;
  11.     for (x = 0; x < r; x++) {
  12.         for (y = 0; y < c; y++) {
  13.             for (z = 0; z < h; z++) {
  14.                 m[x][y][z] = ++a;
  15.             }
  16.         }
  17.     }
  18. }
  19.  
  20. int* testTwo(int r, int c, int h) {
  21.     int* m;
  22.     int x, y, z, a = 0;
  23.     m = malloc(sizeof(int) * c * r * h);
  24.     if (m == NULL) {
  25.         printf("Error allocating memory!");
  26.         exit(1);
  27.     }
  28.     //that's funny, I never though it's like this :o
  29.     //I needed a paper to make some maths
  30.     for (x = 0; x < r*(h + c); x += (h + c)) {
  31.         for (y = 0; y < c * h; y += h) {
  32.             for (z = 0; z < h; z++) {
  33.                 m[x + y + z] = ++a;
  34.             }
  35.         }
  36.     }
  37.     /*
  38.     alternative
  39.     for (z = 0; z < h; z++) {
  40.         for (y = 0; y < c; y++) {
  41.             for (x = 0; x < r; x++) {
  42.                 m[z * (r*r) + y * c + x] = ++a;
  43.             }
  44.         }
  45.     }
  46.     */
  47.     return m;
  48. }
  49.  
  50. int main() {
  51.     int a[2][2][5], x, y, z, rows = 2, cols = 2, height = 5;
  52.     int* b = NULL;
  53.  
  54.     testOne(a, rows, cols, height);
  55.     for (x = 0; x < rows; x++) {
  56.         for (y = 0; y < cols; y++) {
  57.             for (z = 0; z < height; z++) {
  58.                 printf("%d ", a[x][y][z]);
  59.             }
  60.             printf("\n");
  61.         }
  62.     }
  63.     printf("\n\n\n");
  64.     b = testTwo(rows, cols, height);
  65.     for (x = 0; x < rows*(height + cols); x += (height + cols)) {
  66.         for (y = 0; y < cols * height; y += height) {
  67.             for (z = 0; z < height; z++) {
  68.                 printf("%d ", b[x + y + z]);
  69.             }
  70.             printf("\n");
  71.         }
  72.     }
  73.     free(b);
  74.  
  75.     return 1;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement