The realloc function in C is used to dynamically change the size of a previously allocated memory block. The function takes two arguments: a pointer to the previously allocated memory block and the new size of the memory block. The function then returns a pointer to the newly allocated memory block. If the new size is larger than the old size, the extra memory is initialized to zero. If the new size is smaller than the old size, the function may return a pointer to a new memory block with the data from the old memory block copied over.
Syntax :
void* realloc ( void *ptr,size_t new_size )
Example :
int *ptr = ( int * ) malloc( 3 * sizeof( int ) ) ;
int *ptr = ( int * ) realloc ( ptr , 5 * sizeof ( int ) ) ;
Here is an example of how to use the realloc function:
//realloc in Pointers #include<stdio.h> #include<stdlib.h> int main() { //void * realloc(void *ptr,size_t new_size) int i; int *ptr=(int *) malloc(3*sizeof(int)); if(ptr==NULL) { printf("Memory Not Available ..."); exit(1); } printf("\nEnter 3 Nos : \n"); for(i=0; i<3; i++) { scanf("%d",ptr+i); } ptr=(int *) realloc(ptr,5*sizeof(int)); for(i=3; i<5; i++) { scanf("%d",ptr+i); } for(i=0; i<5; i++) { printf("%d ",*(ptr+i)); } return 0; }To download raw file Click Here
Enter 3 Nos : 1 2 3 4 5 1 2 3 4 5
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions