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

如何在C语言中通过指针打印动态分配的字符串?

问题分析与修正

你的代码存在两个致命问题导致无法正常打印字符串,同时还有内存分配的潜在风险,下面逐一说明并修正:

1. 提前释放动态内存

你在打印字符串之前就调用了free(str),这会把分配给字符串的内存归还给系统,之后再访问str指向的内存属于未定义行为,直接导致打印失败。必须把free(str)移到所有字符串操作完成之后。

2. 打印循环的指针/索引逻辑完全错误

原循环:

for(i = *str; i!='\0'; i++){
    printf("%c", *str+i);
}
  • i = *str:这里是把字符串第一个字符的ASCII值赋值给i,不是遍历用的索引;
  • i!='\0':循环条件变成判断字符的ASCII值是否为0,完全不符合遍历字符串的逻辑;
  • *str+i:是把第一个字符的ASCII值加上i,不是读取字符串的第i个字符。

修正后的完整代码

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

int main(){
    char *str = NULL;
    int size = 0;
    int c, i;

    printf("Please enter your command\n");
    while((c = getchar()) != EOF)
    {
        // 用临时指针接收realloc返回值,避免分配失败丢失原内存
        char *temp = realloc(str, size + 1);
        if (temp == NULL) {
            free(str);
            fprintf(stderr, "Memory allocation failed\n");
            return 1;
        }
        str = temp;
        str[size++] = c; 
    }
    // 分配空间存储字符串结束符'\0'
    char *temp = realloc(str, size + 1);
    if (temp == NULL) {
        free(str);
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }
    str = temp;
    str[size] = '\0';  

    printf("\nThe size is %d\n", size);

    // 方法1:用索引遍历字符串
    for(i = 0; str[i] != '\0'; i++){
        printf("%c", str[i]);
    }
    printf("\n");

    // 方法2:用指针直接遍历(符合你想用指针操作的需求)
    char *ptr = str;
    while(*ptr != '\0'){
        printf("%c", *ptr);
        ptr++;
    }
    printf("\n");

    // 所有操作完成后再释放内存
    free(str);
    return 0;
}

额外说明

  • 补充了realloc的返回值检查:realloc失败时会返回NULL,如果直接赋值给str,原来的内存地址会丢失,造成内存泄漏,所以先用临时指针接收,确认成功后再更新str;
  • 指针遍历的方式更贴合你的需求:用ptr指针从字符串起始位置开始,每次判断当前指向的字符是否为'\0',打印后将指针向后移动一位(ptr++),直到遍历完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:15:42