美文网首页
2.6 Growing Arrays

2.6 Growing Arrays

作者: 綿綿_ | 来源:发表于2017-01-12 13:44 被阅读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.

相关文章

  • 2.6 Growing Arrays

    Define a struct Initialize it Expand the capacity once si...

  • rust leetcode median-of-two-sort

    每日小刷 median-of-two-sorted-arrays/ RuntimeMemory0ms2.6m 好好...

  • rust leetcode Longest Substring

    每日小刷 median-of-two-sorted-arrays RuntimeMemory4ms2.6m 好好学...

  • Growing vegetables is growing my

    1 People in India ,regularly judging man’s attitude by ho...

  • Growing

    突然之前的丑了点。

  • Growing

    人生的第一份兼职,开始满腔热血的干活,生怕做错一点被boss批评。慢慢地看淡了,他们的态度,渐渐学会坚守自我...

  • Growing

    《简》简洁,不简单;我正在改变…

  • Growing

    Every day, we grow a little bit. You may like to measure ...

  • 2018-12-06

    Day05.Arrays类加强,Math类详解 1.Arrays类 1.1.Arrays类的概述 Arrays 此...

  • Growing Old Is Easy, Growing up

    时隔这么多年,重新再看小王子,只不过这次看的是英文版的。阅读难度较低,推荐词汇量四级以上人士阅读。 儿时看这本书和...

网友评论

      本文标题:2.6 Growing Arrays

      本文链接:https://www.haomeiwen.com/subject/eborbttx.html