Advertisement
obernardovieira

Matrix vs Malloc (2D array)

Dec 30th, 2015
367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void testOne(int m[][2], int tam) {
  5.     int x;
  6.     for (x = 0; x < tam; x++) {
  7.         m[x][0] = x;
  8.         m[x][1] = x + 1;
  9.     }
  10. }
  11.  
  12. int* testTwo(int tam) {
  13.     int* m;
  14.     int x;
  15.     m = malloc(sizeof(int) * 2 * tam);
  16.     if (m == NULL) {
  17.         printf("Error allocating memory!");
  18.         exit(1);
  19.     }
  20.     for (x = 0; x < tam*2; x+=2) {
  21.         m[x + 0] = x + 1;
  22.         m[x + 1] = x + 2;
  23.     }
  24.     return m;
  25. }
  26.  
  27. //this method is mased in something I found one Internet
  28. //you need to go deeper, and you are doing the same as above
  29. //http://stackoverflow.com/questions/8740195/how-do-we-allocate-a-2-d-array-using-one-malloc-statement
  30. //the method above is what I learned at university
  31. //I think, it's useful if you want an array (with unknown size) of pointers
  32. int** testThree(int tam) {
  33.     int** m, x;
  34.     m = (int**)malloc(tam * sizeof *m + (tam * (2 * sizeof **m)));
  35.     if (m == NULL) {
  36.         printf("Error allocating memory!");
  37.         exit(1);
  38.     }
  39.     for (x = 0; x < tam*2; x+=2) {
  40.         m[x + 0] = (int*)1;
  41.         m[x + 1] = (int*)2;
  42.     }
  43.     return m;
  44. }
  45.  
  46. int main() {
  47.     int a[2][2], x, d = 2;
  48.     int* b = NULL;
  49.     int** c = NULL;
  50.  
  51.     testOne(a, d);
  52.     for (x = 0; x < d; x++) {
  53.         printf("%d, %d\n", a[x][0], a[x][1]);
  54.     }
  55.  
  56.     b = testTwo(d);
  57.     for (x = 0; x < d*2; x+=2) {
  58.         printf("%d, %d\n", b[x + 0], b[x + 1]);
  59.     }
  60.     free(b);
  61.  
  62.     c = testThree(d);
  63.     for (x = 0; x < d*2; x+=2) {
  64.         printf("%d, %d\n", (int)c[x + 0], (int)c[x + 1]);
  65.     }
  66.     free(c);
  67.  
  68.     return 1;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement