C语言增量内存申请 realloc

C语言增量内存申请 realloc

void* realloc (void* ptr, size_t size);
Reallocate memory block

Changes the size of the memory block pointed to by ptr.
The function may move the memory block to a new location (whose address is returned by the function).

The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved to a new location. If the new size is larger, the value of the newly allocated portion is indeterminate.

【如果申请长度小于原来长度,原来内容被截断;等于则内容不变,如果申请长度大于原来长度,多出部分的内存,其内容是不确定的,原来内容不变】

【但不管哪种情况,内存地址都可能改变,相等情况下可能不变】

In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning.

【如果ptr是空,则此时函数相当于malloc的功能】

 代码如下:

 1 /* realloc example: rememb-o-matic */
 2 #include <stdio.h>      /* printf, scanf, puts */
 3 #include <stdlib.h>     /* realloc, free, exit, NULL */
 4 
 5 int main ()
 6 {
 7   int input,n;
 8   int count = 0;
 9   int* numbers = NULL;
10   int* more_numbers = NULL;
11 
12   do {
13      printf ("Enter an integer value (0 to end): ");
14      scanf ("%d", &input);
15      count++;
16 
17      more_numbers = (int*) realloc (numbers, count * sizeof(int));
18 
19      if (more_numbers!=NULL) {
20        numbers=more_numbers;
21        numbers[count-1]=input;
22      }
23      else {
24        free (numbers);
25        puts ("Error (re)allocating memory");
26        exit (1);
27      }
28   } while (input!=0);
29 
30   printf ("Numbers entered: ");
31   for (n=0;n<count;n++) printf ("%d ",numbers[n]);
32   free (numbers);
33 
34   return 0;
View Code

 

posted on 2018-02-09 18:01 时空观察者9号 阅读(...) 评论(...) 编辑 收藏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值