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

如何在指针数组中存储字符串?C语言代码存储失败求助

问题分析与解决方案

你的代码核心问题是局部数组str的内存会在函数结束后被释放,把它的地址赋值给stack_undo[i]后,后续访问这个指针会指向无效内存,导致字符串无法正确保存。另外还有几个细节问题需要修正:

核心问题拆解

  • str是函数内的栈局部变量,write函数执行完毕后,栈上的str内存会被系统回收,stack_undo[i]保存的只是一个失效的内存地址,不是真正的字符串内容。
  • 直接赋值指针只是复制了地址,没有复制字符串本身;如果用字符串拷贝函数但没提前分配内存,会导致内存访问错误。
  • 代码中i的定义和管理缺失,容易出现数组越界;字符串终止符应该用字符'\0'而非指针类型的NULL(虽然多数编译器兼容,但不符合规范)。

修正后的代码

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

char *string_undo[100];
int undo_idx = 0; // 跟踪存储位置,避免越界

void write()
{
    char str[100];
    int m = 0;
    char c;
    printf("\nEnter the string: ");
    
    while (1)
    {
        c = getchar();
        // 跳过输入中的换行符,避免存入无效字符
        if (c == '\n') continue;
        // 遇到'.'停止输入
        if (c == '.') break;
        // 防止str数组越界
        if (m >= 99) break;
        str[m++] = c;
    }
    str[m] = '\0'; // 正确设置字符串终止符

    // 检查undo栈是否已满
    if (undo_idx >= 100)
    {
        printf("Undo stack is full!\n");
        return;
    }

    // 方法1:手动分配内存+拷贝字符串
    string_undo[undo_idx] = malloc(strlen(str) + 1); // +1用于存储'\0'
    if (string_undo[undo_idx] == NULL)
    {
        printf("Memory allocation failed!\n");
        return;
    }
    strcpy(string_undo[undo_idx], str);

    // 方法2:用strdup自动分配内存并拷贝(更简洁)
    // string_undo[undo_idx] = strdup(str);
    // if (string_undo[undo_idx] == NULL)
    // {
    //     printf("Memory allocation failed!\n");
    //     return;
    // }

    undo_idx++;
}

关键修正点说明

  1. 动态分配内存:给string_undo[undo_idx]分配堆内存(malloc或strdup),堆内存不会随函数结束被释放,能持久保存字符串内容。
  2. 内存分配检查:必须检查malloc/strdup的返回值,避免内存分配失败导致的程序崩溃。
  3. 索引管理:用undo_idx跟踪指针数组的存储位置,每次存储后递增,同时检查是否超过数组容量,防止越界。
  4. 输入处理优化:跳过换行符,避免把用户输入时的回车存入字符串;限制m的最大值,防止str数组越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:50:33