分享几个例子,记住

1.calloc动态内存分配

#include<stdio.h>

#include <stdlib.h>

int main ()

{

  int i,n;

  int * pData;

  printf ( "Amount of numbers to be entered: " );

  scanf ( "%d",&i);

  pData = ( int*) calloc (i,sizeof (int)); //i表示要开内存个数

  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);

     pData = NULL;

  return 0;

}

2.malloc动态内存分配

/* malloc example: string 产生*/

#include <stdio.h>

#include <stdlib.h>

int main ()

{

  int i,n;

  char * buffer;

  printf ( "How long do you want the string? " );

  scanf ( "%d", &i);

  buffer = ( char*) malloc (i+1);//i+1字符串末尾有“\0”

  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)

    buffer[n]=rand()%26+ 'a';

  buffer[i]= '\0';

  printf ( "Random string: %s\n",buffer);

  free (buffer);

  buffer = NULL;//最好付空

  return 0;

}

3.realloc动态分配内存

/* realloc example: 动态扩容*/

#include <stdio.h>

#include <stdlib.h>

int main ()

{

  int input,n;

  int count=0;

  int * numbers = NULL;

  int * more_numbers;

  do {

     printf ( "Enter an integer value (0 to end): " );

     scanf ( "%d", &input);

     count++;

     //检查number大小,够就赋值过去,不够,重新分配,最后释放

     more_numbers = ( int*) realloc (numbers, count * sizeof(int ));

     if (more_numbers!=NULL) {

       numbers=more_numbers;//改变指针指向

       numbers[count-1]=input;//赋值

     }

     else {

       free (numbers);//大空间分配失败,先释放空间,之后退出

       puts ( "Error (re)allocating memory" );

       exit (1);

     }

  } while (input!=0);

  printf ( "Numbers entered: ");

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

  free (numbers);//释放

  return 0;

}