如何用realloc给一个初始定义了的数组再次扩展内存
详解和代码要求
使用C语言
关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言在使用realloc()重新分配内存时,我们需要注意一些细节,以确保程序的正确性和安全性。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, old_size = 5, new_size = 10;
int *ptr = (int *)malloc(old_size * sizeof(int));
if (ptr == NULL)
{
printf("Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < old_size; i++)
{
ptr[i] = i;
}
//backup old pointer
int *old_ptr = ptr;
//resize memory block
ptr = (int *)realloc(ptr, new_size * sizeof(int));
if (ptr == NULL)
{
printf("Memory reallocation failed!\n");
free(old_ptr);
exit(EXIT_FAILURE);
}
//initialize new memory
for (i = old_size; i < new_size; i++)
{
ptr[i] = i;
}
//print results
for (i = 0; i < new_size; i++)
{
printf("%d ", ptr[i]);
}
printf("\n");
//free memory
free(ptr);
return 0;
}
在上述代码中,我们首先分配了一个大小为5的数组,然后将其初始化为0~4,接着将旧的指针备份,然后使用realloc()函数将内存块扩展至10个元素,如果realloc()执行成功,则将新分配的空间进行初始化为5~9,最后打印数组的值,释放指针指向的内存。如果realloc()函数执行失败,则需要进行错误处理,即释放备份指向的内存,并打印错误信息,程序退出。