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,868評論 0 23
  • 如果我告訴你 三年前的那朵花,還在開著 你是否愿意。來看看 包括你指過的那朵云,亦在天空飄著,被舉的高高, 你是否...
    鯨香閱讀 244評論 0 0
  • 夜,瘦了梧桐老樹 瘦了秋日荷塘 相思的窗前 如水的月光 淡白在素雅的箋頁 層層疊疊的思念 在筆尖徘徊不前 千言萬語...
    yzwjjx閱讀 110評論 0 0
  • 每天總是會有不一樣的煩惱,打電話爸媽說弟弟又不聽話了,男朋友讓關注房產可看著價格又太貴買不起了,天氣冷的腳都動不了...
    御馬閱讀 358評論 0 0
  • 4月25號 陰天 郴州 還有幾天就到5.1了,每年的5.1我都在期待著。我的期待沒人懂,也沒說過,有時有心的說岀...
    馨之芬芳閱讀 213評論 0 1