Advertisement
RicardasSim

realloc, pointer

Jul 6th, 2019
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.80 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5.  
  6. int main()
  7. {
  8.  
  9.     int *arr;
  10.     int *tmpArr;
  11.     int *pCur;
  12.     unsigned int i;
  13.    
  14.    
  15.    
  16.     arr = malloc(10*sizeof arr[0]);
  17.    
  18.     printf("arr adress:%p\narr ",(void*)arr);
  19.    
  20.     if(!arr)
  21.     {
  22.         printf("memory allocation error.\n");
  23.         return 1;
  24.     }
  25.    
  26.     for(i=0; i<10; ++i)
  27.     {
  28.         arr[i] = i;
  29.         printf("%d ",arr[i]);
  30.     }
  31.  
  32.     printf("\npCur ");
  33.  
  34.     pCur = arr;
  35.    
  36.     printf("%d ", *pCur);
  37.    
  38.     pCur++;
  39.    
  40.     printf("%d \n", *pCur);
  41.  
  42.     //increase
  43.    
  44.     tmpArr = realloc(arr,12*sizeof arr[0]);
  45.    
  46.     if(!tmpArr)
  47.     {
  48.         printf("memory reallocation error (1).\n");
  49.         free(arr);
  50.         return 1;
  51.     }    
  52.    
  53.     arr = tmpArr;
  54.    
  55.     printf("arr adress:%p\narr ",(void*)arr);
  56.    
  57.     arr[10]=10;
  58.     arr[11]=11;
  59.    
  60.     for(i=0; i<12; ++i) printf("%d ",arr[i]);
  61.    
  62.     printf("\npCur ");    
  63.  
  64.     pCur = arr;
  65.    
  66.     printf("%d ", *pCur);
  67.    
  68.     pCur++;
  69.    
  70.     printf("%d \n", *pCur);
  71.    
  72.     //shrink
  73.    
  74.     tmpArr = realloc(arr,8*sizeof arr[0]);
  75.    
  76.     if(!tmpArr)
  77.     {
  78.         printf("memory reallocation error (2).\n");
  79.         free(arr);
  80.         return 1;
  81.     }
  82.    
  83.     arr = tmpArr;
  84.    
  85.     printf("arr adress:%p\narr ",(void*)arr);
  86.    
  87.     for(i=0; i<8; ++i) printf("%d ",arr[i]);
  88.    
  89.     printf("\npCur ");
  90.  
  91.     pCur = arr;
  92.    
  93.     printf("%d ", *pCur);
  94.    
  95.     pCur++;
  96.    
  97.     printf("%d \n", *pCur);    
  98.    
  99.     free(arr);
  100.    
  101.     return 0;
  102. }
  103.  
  104. /*
  105.  
  106. output:
  107.  
  108. arr adress:0x556d786f4260
  109. arr 0 1 2 3 4 5 6 7 8 9
  110. pCur 0 1
  111. arr adress:0x556d786f46a0
  112. arr 0 1 2 3 4 5 6 7 8 9 10 11
  113. pCur 0 1
  114. arr adress:0x556d786f46a0
  115. arr 0 1 2 3 4 5 6 7
  116. pCur 0 1
  117.  
  118. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement