Advertisement
Guest User

Prelab5.c

a guest
Feb 18th, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. // Don't steal my stuff btw I will find you
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. typedef struct
  7. {
  8. int rows, columns;
  9. } TableDimensions;
  10.  
  11. void ** createTable(int rows, int columns, int elementSize)
  12. {
  13. void ** table = malloc(rows * sizeof(void *));
  14. *table = malloc(columns * elementSize + sizeof(TableDimensions));
  15. for(int i = 1; i<rows; i++)
  16. {
  17. *(table + i) = malloc(columns * elementSize);
  18. }
  19. TableDimensions test = {rows, columns};
  20. **((TableDimensions **)table) = test;
  21. *table += sizeof(TableDimensions);
  22.  
  23. return (void **)table;
  24. }
  25.  
  26. int getRows(void ** table)
  27. {
  28. return ((TableDimensions *)((*table) - sizeof(TableDimensions)))->rows;
  29. }
  30.  
  31. int getColumns(void ** table)
  32. {
  33. return ((TableDimensions *)((*table) - sizeof(TableDimensions)))->columns;
  34. }
  35.  
  36. void freeTable(void ** table)
  37. {
  38. free(*table - sizeof(TableDimensions));
  39. table = NULL;
  40. return;
  41. }
  42.  
  43. int main(void)
  44. {
  45. int rows = 10, columns = 10;
  46. int ** table = (int **)createTable(rows, columns, sizeof(int));
  47. printf("The array values are:\n");
  48.  
  49. // Initialize array values and print them at the same time
  50. int counter = 0;
  51. for(int i = 0; i<getRows((void **)table); i++)
  52. {
  53. for(int j = 0; j<getColumns((void **)table); j++)
  54. {
  55. counter++;
  56. table[i][j] = counter;
  57. printf("%d\t", table[i][j]);
  58. }
  59. puts("");
  60. }
  61.  
  62. freeTable((void **)table);
  63.  
  64. puts("Program has finished.");
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement