2.6 Growing Arrays

2017-01-12  本文已影响0人  綿綿_

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<a.size;i++)
   {
     printf("%d",a.data[i]); // notice here, a.data[i] 
   }
   FREE(&a);
   return 0;
}

View complete code here.

上一篇 下一篇

猜你喜欢

热点阅读