C - String Manipulation Functions, realloc
Tutorials Point


  Learning C
  C Function References
  C Useful Resources
  Selected Reading

Copyright © 2014 by tutorialspoint



  Home     References     About TP     Advertising  

C - realloc function

previous

Synopsis:

#include <stdio.h>

void *realloc(void *mem_address, int newsize); 

Description:

The size of the memory block pointed to by the mem_address parameter is changed to the newsize bytes, expanding or reducing the amount of memory available in the block.

In case that mem_address is NULL, the function behaves exactly as malloc, assigning a new block of newsize bytes and returning a pointer to the beginning of it.

In case that the newsize is 0, the memory previously allocated in mem_address is deallocated as if a call to free was made, and a NULL pointer is returned.

Return Value

A pointer to the reallocated memory block, which may be either the same as the mem_address argument or a new location.

Example

#include <stdio.h>

int main ()
{
  int input,n;
  int count=0;
  int * numbers = NULL;

  do {
     printf ("Enter an integer value (0 to end): ");
     scanf ("%d", &input);
     count++;
     numbers = (int*) realloc (numbers, count * sizeof(int));
     if (numbers==NULL)
       { puts ("Error (re)allocating memory"); exit (1); }
     numbers[count-1]=input;
  } while (input!=0);

  printf ("Numbers entered: ");
  for (n=0;n<count;n++) printf ("%d ",numbers[n]);
  free (numbers);

  return 0;
}

It will proiduce following result:

Enter an integer value (0 to end): 2
Enter an integer value (0 to end): 3
Enter an integer value (0 to end): 4
Enter an integer value (0 to end): 5
Enter an integer value (0 to end): 0
Numbers entered: 2 3 4 5 0


previous Printer Friendly

Advertisements


  

Advertisements



Advertisements