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

printf函数未输出指定字符串,C语言代码调试求助

问题分析

你的代码核心问题是所有存入words数组的指针都指向同一个栈上的current_word数组:

  • current_word是main函数内的局部数组,每次调用read_line都会覆盖它的内容;
  • 执行*(words + n_words) = current_word;时,只是把current_word的内存地址存入words,并没有复制字符串本身;
  • 最后遍历words打印时,所有指针都指向同一块内存区域——要么是最后一次输入的内容,要么如果最后输入空行,current_word会是空字符串,最终看起来像什么都没输出。
修复方案

为每个输入的字符串分配独立的堆内存,保存字符串副本,而非直接存储栈数组的地址:

  • 用strdup函数(POSIX标准,自动分配内存并复制字符串),或手动用malloc+strcpy实现;
  • 程序结束前释放所有分配的内存,避免内存泄漏。
修改后的代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "readline.h"

#define MAX_WORDS 10

int compare_words (const void * p, const void * q);

int main (void) {
    char current_word[20];
    char ** words = malloc (sizeof (char *) * MAX_WORDS);
    if (words == NULL) {
        printf ("Could not allocate enough memory for the variable\n");
        exit (EXIT_FAILURE);
    }
    int n_words = 0, i;

    for (;;) {
        if (n_words == MAX_WORDS) {
            printf ("Cannot assign more memory to the program.\n" 
            "Proceding to display the elements in order: \n");
            break;
        }
        printf ("Enter a sentence: ");
        read_line(current_word, 20);

        if (current_word[0] != '\0') {
            // 为当前字符串分配内存并复制内容
            *(words + n_words) = strdup(current_word);
            // 检查内存分配是否成功
            if (*(words + n_words) == NULL) {
                printf("Failed to allocate memory for word\n");
                // 释放已分配的内存
                for (int j = 0; j < n_words; j++) {
                    free(words[j]);
                }
                free(words);
                exit(EXIT_FAILURE);
            }
            n_words++;
        } else {
            break;
        }
    }

    qsort(words, n_words, sizeof(char *), compare_words);
    printf("\nIn sorted order: ");

    for (i = 0; i < n_words; i++)
        printf("%s ", *(words + i));
    printf("\n");

    // 释放所有分配的内存
    for (i = 0; i < n_words; i++) {
        free(words[i]);
    }
    free(words);

    return 0;
}

int compare_words (const void *p, const void *q) {
    return strcmp (*(char **) p, *(char **) q);
}
额外说明

如果你的环境不支持strdup,可以替换为以下代码实现相同功能:

*(words + n_words) = malloc(strlen(current_word) + 1);
if (*(words + n_words) != NULL) {
    strcpy(*(words + n_words), current_word);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 06:32:50