Home >Backend Development >C++ >In C language, what does Realloc mean?
The C library's memory allocation function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated using malloc or calloc calls.
Memory can be allocated in the following two ways:
Once memory is allocated at compile time, it cannot Changed during execution. Either there is insufficient memory or it is a waste of memory.
The solution is to create memory dynamically, that is, according to the needs of the program during execution.
The standard library functions for dynamic memory management are as follows:
is used to reallocate allocated memory.
You can reduce or increase the allocated memory.
Returns a void pointer pointing to the base address of the reallocated memory.
The syntax of the realloc() function is as follows:
Free void *realloc (pointer, newsize);
The following example shows the usage of the realloc() function.
int *ptr; ptr = (int * ) malloc (1000);// we can use calloc also - - - - - - - - - ptr = (int * ) realloc (ptr, 500); - - - - - - ptr = (int * ) realloc (ptr, 1500);
The following is a C program using the realloc() function:
Online demonstration
#include<stdio.h> #include<stdlib.h> int main(){ int *ptr, i, num; printf("array size is 5</p><p>"); ptr = (int*)calloc(5, sizeof(int)); if(ptr==NULL){ printf("Memory allocation failed"); exit(1); // exit the program } for(i = 0; i < 5; i++){ printf("enter number at %d: ", i); scanf("%d", ptr+i); } printf("</p><p>Let's increase the array size to 7</p><p> "); ptr = (int*)realloc(ptr, 7 * sizeof(int)); if(ptr==NULL){ printf("Memory allocation failed"); exit(1); // exit the program } printf("</p><p> enter 2 more integers</p><p></p><p>"); for(i = 5; i < 7; i++){ printf("Enter element number at %d: ", i); scanf("%d", ptr+i); } printf("</p><p> result array is: </p><p></p><p>"); for(i = 0; i < 7; i++){ printf("%d ", *(ptr+i) ); } return 0; }
When the above program When executed, it produces the following result −
array size is 5 enter number at 0: 23 enter number at 1: 12 enter number at 2: 45 enter number at 3: 67 enter number at 4: 20 Let's increase the array size to 7 enter 2 more integers Enter element number at 5: 90 Enter element number at 6: 60 result array is: 23 12 45 67 20 90 60
The above is the detailed content of In C language, what does Realloc mean?. For more information, please follow other related articles on the PHP Chinese website!