realloc() 的一点小技巧

参考:

http://www.cplusplus.com/reference/cstdlib/realloc/

https://www.geeksforgeeks.org/how-to-deallocate-memory-without-using-free-in-c/

函数原型: 

void *realloc(void *ptr,size_t size);

如果 ptr = NULL,就相当于调用 malloc(size) 

如果 ptr != NULL && size = 0,就相当于调用 free(ptr),ptr 指向的对象会被释放。

例子:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int main(void)
 5 {
 6     int count,input;
 7     int *numbers,*morenumbers;
 8     count = 0;
 9     numbers = morenumbers = NULL;
10 
11     do{
12         printf("Enter an integer(0 to quit): ");
13         scanf("%d",&input);
14         count++;
15         morenumbers = (int *)realloc(numbers,count * sizeof(int));// *.*
16         if(morenumbers == NULL)
17         {
18             puts("(re)alloc failed.");
19             exit(EXIT_FAILURE);
20         }
21         numbers = morenumbers;
22         numbers[count - 1] = input;    
23     }while(input != 0);
24     puts("Number entered:");
25     for(int i = 0; i < count - 1; ++i) // get rid of 0
26         printf("%d ",numbers[i]);
27     free(numbers);
28 
29     return 0;
30 }

结果:

Enter an integer(0 to quit): 1
Enter an integer(0 to quit): 2
Enter an integer(0 to quit): 3
Enter an integer(0 to quit): 4
Enter an integer(0 to quit): 5
Enter an integer(0 to quit): 6
Enter an integer(0 to quit): 7
Enter an integer(0 to quit): 8
Enter an integer(0 to quit): 9
Enter an integer(0 to quit): 0
1 2 3 4 5 6 7 8 9

原文地址:https://www.cnblogs.com/luwudang/p/9770876.html