Tucancitto

FP - lucru cu pointeri (vectori)

Jan 31st, 2021 (edited)
863
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. int Separare(int dim, int* vector, int* dimPozitive, int** vectorPozitive, int* dimNegative, int** vectorNegative)
  5. {
  6.     *vectorPozitive = (int**)calloc(dim + 1, sizeof(int*));
  7.     if (!*vectorPozitive)
  8.         return 0;
  9.  
  10.     *vectorNegative = (int**)calloc(dim + 1, sizeof(int*));
  11.     if (!*vectorNegative)
  12.     {
  13.         free(*vectorPozitive);
  14.         return 0;
  15.     }
  16.  
  17.     for (int i = 0; i < dim; i++)
  18.         if (vector[i] > 0)
  19.             (*vectorPozitive)[(*dimPozitive)++] = vector[i];
  20.         else
  21.             if (vector[i] < 0)
  22.                 (*vectorNegative)[(*dimNegative)++] = vector[i];
  23.  
  24.     return 1;
  25. }
  26.  
  27. void main()
  28. {
  29.     int* vector, dim;
  30.     int* vectorPozitive, dimPozitive = 0;
  31.     int* vectorNegative, dimNegative = 0;
  32.  
  33.     scanf_s("%d", &dim);
  34.  
  35.     vector = (int*)calloc(dim + 1, sizeof(int));
  36.     if (!vector)
  37.         return 0;
  38.  
  39.     for (int i = 0; i < dim; i++)
  40.         scanf_s("%d", &vector[i]);
  41.  
  42.     if (Separare(dim, vector, &dimPozitive, &vectorPozitive, &dimNegative, &vectorNegative))
  43.     {
  44.         printf("Pozitive: ");
  45.         for (int i = 0; i < dimPozitive; i++)
  46.             printf("%d ", vectorPozitive[i]);
  47.  
  48.         puts("");
  49.  
  50.         printf("Negative: ");
  51.         for (int i = 0; i < dimNegative; i++)
  52.             printf("%d ", vectorNegative[i]);
  53.  
  54.         free(vectorPozitive);
  55.         free(vectorNegative);
  56.     }
  57.  
  58.     free(vector);
  59. }
Add Comment
Please, Sign In to add comment