Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2013
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct matrix
  5. {
  6.     int** tab;
  7.     unsigned w;
  8.     unsigned h;
  9. };
  10.  
  11. typedef struct matrix Matrix;
  12.  
  13. void init(Matrix* m, unsigned w, unsigned h)
  14. {
  15.     unsigned i;
  16.     m->w = w;
  17.     m->h = h;
  18.     m->tab = (int**)malloc(w*sizeof(int*));
  19.     for(i = 0; i < w; ++i)
  20.         m->tab[i] = (int*)malloc(h*sizeof(int));
  21. }
  22.  
  23. void clean(Matrix* m)
  24. {
  25.     unsigned i;
  26.     for(i = 0; i < m->w; ++i)
  27.         free(m->tab[i]);
  28.     free(m->tab);
  29. }
  30.  
  31. void save(Matrix* m, const char* path)
  32. {
  33.     unsigned i;
  34.     FILE* f = fopen(path, "wb");
  35.     for(i = 0; i < m->w; ++i)
  36.         fwrite((m->tab[i]), sizeof(int), m->h, f);
  37.     fclose(f);
  38. }
  39.  
  40. void load(Matrix* m, const char* path)
  41. {
  42.     unsigned i;
  43.     FILE* f = fopen(path, "rb");
  44.     for(i = 0; i < m->w; ++i)
  45.         fread((m->tab[i]), sizeof(int), m->h, f);
  46.     fclose(f);
  47. }
  48.  
  49. void fill(Matrix* m, int f)
  50. {
  51.     unsigned i, j;
  52.     for(i = 0; i < m->w; ++i)
  53.         for(j = 0; j < m->h; ++j)
  54.             m->tab[i][j] = f;
  55.        
  56. }
  57.  
  58. void display(Matrix* m)
  59. {
  60.     unsigned i, j;
  61.     for(i = 0; i < m->w; ++i)
  62.     {
  63.         for(j = 0; j < m->h; ++j)
  64.         {
  65.             printf("%d ", m->tab[i][j]);
  66.         }
  67.         printf("\n");
  68.     }
  69. }
  70.  
  71. int main(int argc, char** argv)
  72. {
  73.     Matrix src, dst;
  74.     init(&src, 5, 5);
  75.     init(&dst, 5, 5);
  76.     fill(&src, 13);
  77.     fill(&dst, 0);
  78.     display(&src);
  79.     display(&dst);
  80.     printf("\n\n");
  81.     save(&src, "pliczek.lol");
  82.     load(&dst, "pliczek.lol");
  83.     display(&dst);
  84.     clean(&src);
  85.     clean(&dst);
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement