Advertisement
GreMendes

Realloc

Sep 4th, 2014
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdlib.h>
  3. using namespace std;
  4.  
  5.  
  6. void preencheInteiros(int* vetor, int tamanho){
  7.  
  8.     for (int i = 0; i < tamanho; i++)
  9.         vetor[i] = i * i;
  10.  
  11. }
  12.  
  13. void exibirArray(int* vetor, int tamanho){
  14.     cout << "Exibindo o array:" << endl;
  15.     for (int i = 0; i < tamanho; i++){
  16.        
  17.         cout << vetor[i] << "  ";
  18.     }
  19.  
  20. }
  21.  
  22. int main(){
  23.  
  24.     int n;
  25.     cout << "Digite o tamanho do array" << endl;
  26.     cin >> n;
  27.  
  28.     int* meuArray;
  29.     meuArray = (int*)malloc(sizeof(int)* n);   
  30.     preencheInteiros(meuArray, n);
  31.     exibirArray(meuArray, n);
  32.     int n2;
  33.     cout << endl
  34.         << "Qual deve ser o novo tamanho do array?" << endl;
  35.     cin >> n;
  36.  
  37.     if (n > 0){
  38.  
  39.         int* novoArray;
  40.         novoArray = (int *)realloc(meuArray, sizeof(int)* n);
  41.         exibirArray(novoArray,n);
  42.         if (novoArray == NULL){
  43.             cout << endl << "Ocorreu um erro ao alocar o novo espaço!";
  44.            
  45.         }
  46.        
  47.     }
  48.     else{
  49.         cout << endl << "O numero do vetor deve ser maior que 0";
  50.  
  51.     }
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement