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

View complete code here.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,890评论 0 23
  • 如果我告诉你 三年前的那朵花,还在开着 你是否愿意。来看看 包括你指过的那朵云,亦在天空飘着,被举的高高, 你是否...
    鲸香阅读 244评论 0 0
  • 夜,瘦了梧桐老树 瘦了秋日荷塘 相思的窗前 如水的月光 淡白在素雅的笺页 层层叠叠的思念 在笔尖徘徊不前 千言万语...
    yzwjjx阅读 111评论 0 0
  • 每天总是会有不一样的烦恼,打电话爸妈说弟弟又不听话了,男朋友让关注房产可看着价格又太贵买不起了,天气冷的脚都动不了...
    御马阅读 359评论 0 0
  • 4月25号 阴天 郴州 还有几天就到5.1了,每年的5.1我都在期待着。我的期待没人懂,也没说过,有时有心的说岀...
    馨之芬芳阅读 213评论 0 1