relloc explaination

本文详细解析了realloc函数的原型,语法及使用方法。realloc用于改变已分配内存块的大小,返回指向新分配内存的指针,若失败则返回NULL。新大小可大于或小于原大小,可能导致数据未初始化或丢失。

the prototype of relloc is extern void *realloc(void *men_address, unsigned int newsize)

grammar
pointer name = (data type*)realloc(the name of the pointer which point to the memory that need to be changed, the new size)
the new size maybe smaller or bigger than the old size(if the new size is larger than the original memory size, the new allocation part will not be initialized; if the new size is smaller than tne original memory size, it maybe cause data loss[1-2])
语法
指针名=(数据类型*)realloc(要改变内存大小的指针名,新的大小)。
新的大小可大可小(如果新的大小大于原内存大小,则新分配部分不会被初始化;如果新的大小小于原内存大小,可能会导致数据丢失[1-2] )

returns a pointer to the allocated memory if the reassignment is successful, otherwise return NULL pointer;

如果重新分配成功则返回指向被分配内存的指针,否则返回空指针NULL

转载于:https://www.cnblogs.com/1915884031A-qqcom/p/7672884.html

11-01
在 C 语言实现栈的场景下,`realloc` 函数用于动态调整栈的容量。当栈满时,需要对栈的存储空间进行扩容,以容纳更多的元素。 以下是在栈的入栈操作中使用 `realloc` 函数的示例代码: ```c #include <stdlib.h> #include <assert.h> #include <stdbool.h> #include <stdio.h> // 定义栈的数据类型 typedef int STDataType; // 定义栈的结构体 typedef struct Stack { STDataType* a; int top; // 栈顶 int capacity; // 栈的容量 } ST; // 初始化栈 void STInit(ST* pst) { assert(pst); pst->a = NULL; pst->top = 0; pst->capacity = 0; } // 入栈 void STPush(ST* pst, STDataType data) { assert(pst); if (pst->top == pst->capacity) { int newCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2; STDataType* tmp = (STDataType*)realloc(pst->a, newCapacity * sizeof(STDataType)); if (tmp == NULL) { printf("realloc failed\n"); exit(-1); } pst->a = tmp; pst->capacity = newCapacity; } pst->a[pst->top] = data; pst->top++; } // 其他栈操作函数... int main() { ST st; STInit(&st); STPush(&st, 1); STPush(&st, 2); STPush(&st, 3); // 其他操作... return 0; } ``` 在上述代码中,`STPush` 函数用于将元素压入栈中。当栈的当前元素数量 `pst->top` 等于栈的容量 `pst->capacity` 时,说明栈已满,需要进行扩容操作。使用 `realloc` 函数将栈的容量扩大为原来的两倍(如果初始容量为 0,则初始化为 4)。 `realloc` 函数的使用需要注意以下几点: - `realloc` 函数的第一个参数是指向之前分配的内存块的指针,如果该指针为 `NULL`,则 `realloc` 行为与 `malloc` 相同。 - `realloc` 函数的第二个参数是新分配的大小(以字节为单位)。 - `realloc` 函数返回一个指向调整大小后的内存块的指针。如果调整大小失败,则返回 `NULL`。因此,在使用 `realloc` 函数后,需要检查返回的指针是否为 `NULL`,以避免潜在的空指针引用错误[^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值