Tutorials Point


  Learning C
  C Function References
  C Useful Resources
  Selected Reading

Copyright © 2014 by tutorialspoint



  Home     References     About TP     Advertising  

C - malloc function

previous

Synopsis:

#include <stdio.h>

void * malloc ( int size );

Description:

Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.

Return Value

On success, a pointer to the memory block allocated by the function. If fails a NULL value is returned.

Example

#include <stdio.h>

int main ()
{
  int i,n;
  int * pData;
  printf ("Amount of numbers to be entered: ");
  scanf ("%d",&i);
  pData = (int*) malloc (i*sizeof(int));
  if (pData==NULL) exit (1);
  for (n=0;n<i;n++)
  {
    printf ("Enter number #%d: ",n);
    scanf ("%d",&pData[n]);
  }
  printf ("You have entered: ");
  for (n=0;n<i;n++) printf ("%d ",pData[n]);
  free (pData);
  return 0;
}

It will proiduce following result:

Amount of numbers to be entered: 10
Enter number #0: 2
Enter number #1: 3
Enter number #2: 3
Enter number #3: 4
Enter number #4: 5
Enter number #5: 6
Enter number #6: 7
Enter number #7: 8
Enter number #8: 3
Enter number #9: 9
You have entered: 2 3 3 4 5 6 7 8 3 9


previous Printer Friendly

Advertisements


  

Advertisements