You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C语言动态数组代码中添加realloc功能实现扩容后打印结果

原有代码已知问题

  • 变量拼写错误:输入元素时使用了未定义的padados,实际应为已定义的动态数组指针pdados
  • 缺少扩容逻辑的实现,未处理新增元素的输入和扩容后的输出

修改后完整可运行代码

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i;
    int total;
    int* pdados;
    printf("请输入初始元素个数:");
    scanf("%i", &total);
    pdados = (int *) malloc( total * sizeof(int) );
    if ( pdados == NULL ) {
        printf("内存申请失败\n");
        return -1;
    }
    for ( i = 0; i < total; i++ ) {
        printf("请输入第%d个元素的值:", i + 1);
        scanf("%i", &pdados[i]);
    }
    printf("已输入的初始元素为:");
    for ( i = 0; i < total; i++ ) {
        printf(" %i", pdados[i]);
    }
    printf("\n");

    // ========== realloc 扩容逻辑实现 ==========
    int add_cnt;
    printf("请输入需要新增的元素个数:");
    scanf("%i", &add_cnt);
    int new_total = total + add_cnt;
    // 用临时指针接收realloc返回值,避免申请失败导致原指针丢失、内存泄漏
    int *temp_p = (int *)realloc(pdados, new_total * sizeof(int));
    if (temp_p == NULL) {
        printf("扩容失败\n");
        // 扩容失败也要释放原申请的内存
        free(pdados);
        return -1;
    }
    // 扩容成功,更新指针和总长度
    pdados = temp_p;
    // 输入新增的元素
    for (i = total; i < new_total; i++) {
        printf("请输入第%d个新增元素的值:", i - total + 1);
        scanf("%i", &pdados[i]);
    }
    // 更新总元素数
    total = new_total;

    // 输出全部元素
    printf("扩容后的全部元素为:");
    for (i = 0; i < total; i++) {
        printf(" %i", pdados[i]);
    }
    printf("\n");

    free(pdados);
    return 0;
}

实现核心说明

  • realloc调用必须使用临时指针接收返回值,若直接赋值给原指针,一旦内存申请失败返回NULL,会丢失原内存地址导致内存泄漏
  • 扩容后输入元素的起始下标为扩容前的总长度,避免覆盖原有已存储的元素
  • 所有动态申请的内存无论操作成功失败都要释放,避免内存泄漏

内容的提问来源于stack exchange,提问作者neves neves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 09:54:02