2.6 Growing Arrays

Define a struct

struct array
{
  int *data;
  int capacity;
  int size;
};

Initialize it

void initialize(struct array *p)
{
   p->capacity=1;
   p->data=(int*)malloc(p->capacity*sizeof(int));
   p->size=0;
}

Expand the capacity once size=capacity
The call to realloc grows the array to the new size, preserving the existing elements, and returns a pointer to it or NULL if there isn't enough memory.

void expand(struct array *p,int a)
{
  if(p->size == p->capacity)
    {
      p->capacity=p->capacity*2;
      p->data=realloc(p->data,p->capacity*sizeof(int));
    }
  p->data[p->size++]=a;
}

Never forget FREE

void FREE(struct array *p)
{
  free(p->data);
  p->size=0;
  p->capacity=1;
}

main part

int main()
{
  struct array a;
  int i,x;
  initialize(&a);
  printf("Enter the number\n");
while(1)
{
if(scanf("%d",&x) ==EOF)
   {
      printf("End of input\n");
      break;
   }
   else
     expand(&a,x);
}
   for(i=0;i

View complete code here.

你可能感兴趣的:(2.6 Growing Arrays)