Advertisement
Eduardo_Pires

vetor dinâmico

Aug 28th, 2022
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include<stdlib.h>
  2. #include<stdio.h>
  3. #include<stdbool.h>
  4. #include<math.h>
  5.  
  6. struct vetor {
  7.     float *elem;
  8.     int total;
  9.     int max;
  10. };
  11.  
  12. typedef struct vetor Vetor;
  13.  
  14. Vetor *criar(int n, bool *deuCerto)
  15. {
  16.     Vetor *v;
  17.     v = (Vetor *) malloc(sizeof(Vetor));
  18.     if (v == NULL) *deuCerto = false;
  19.     else {
  20.         // precisamos do else pois, se não deu certo, não podemos alocar o array
  21.         v->elem = (float *) malloc(n * sizeof(float));
  22.         if (v->elem == NULL) *deuCerto = false;
  23.         else {
  24.             *deuCerto = true;
  25.             v->total = 0;
  26.             v->max = n;
  27.         }
  28.     }
  29.  
  30.     return v;
  31. }
  32.  
  33. void destruir(Vetor *v)
  34. {
  35.     free(v->elem);
  36.     free(v);
  37. }
  38.  
  39. bool cheio(Vetor *v)
  40. {
  41.     if (v->total == v->max)
  42.         return true;
  43.     else
  44.         return false;
  45. }
  46.  
  47. void inserir(Vetor *v, float X, bool *deuCerto)
  48. {
  49.     if (cheio(v) == false) {
  50.         *deuCerto = true;
  51.         v->elem[v->total] = X;
  52.         v->total = v->total + 1;
  53.     } else {
  54.         *deuCerto = false;
  55.     }
  56. }
  57.  
  58. bool vazio(Vetor *v)
  59. {
  60.     if (v->total == 0)
  61.         return true;
  62.     else
  63.         return false;
  64. }
  65.  
  66. void mostrar(Vetor *v, int index, float *X, bool *deuCerto)
  67. {
  68.     if (vazio(v) == false) {
  69.         if (index >= 0 && index < v->max) {
  70.             *deuCerto = true;
  71.             *X = v->elem[index];
  72.         } else *deuCerto = false;
  73.     } else *deuCerto = false;
  74. }
  75.  
  76. int main()
  77. {
  78.     bool deuCerto;
  79.     Vetor *v;
  80.     int i, n;
  81.     float valor;
  82.  
  83.     printf("Digite o tamanho do vetor: ");
  84.     scanf("%d", &n);
  85.        
  86.     v = criar(n, &deuCerto);
  87.     if (deuCerto == false) {
  88.         printf("Erro ao criar vetor\n");
  89.         exit(1);
  90.     }
  91.  
  92.     i = 1;
  93.     while (cheio(v) == false) {
  94.         inserir(v, sqrt(i), &deuCerto);
  95.         i = i+1;
  96.     };
  97.  
  98.     i = 0;
  99.     do {
  100.         mostrar(v, i, &valor, &deuCerto);
  101.         printf("%f ", valor);
  102.         i = i+1;
  103.     } while (deuCerto == true);
  104.     printf("\n");
  105.  
  106.     destruir(v);
  107.  
  108.     return 0;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement