C 语言中 realloc() 的使用
realloc 函数用于修改之前由 malloc 或 calloc 分配的内存块大小。
以下是 C 语言中 realloc 的语法:
void *realloc(void *pointer, size_t size)
其中,
指针 - 指向之前由 malloc 或 calloc 分配的内存块的指针。
size - 新的内存块大小。
以下是 C 语言中 realloc() 的示例:
示例
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
p = (int*) realloc(p, 6);
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
return 0;
}输出
Enter elements of array : 3 34 28 8 Sum : 73 Enter elements of array : 3 28 33 8 10 15 Sum : 145
在上面的程序中,内存块由 calloc() 分配,并计算元素的和。之后,realloc() 将内存块的大小从 4 调整为 6 并计算其和。
p = (int*) realloc(p, 6);
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP