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

C语言中按行输入带空格的字符数组的代码问题排查

Issues in Your C Code & Fixed Version

Let's walk through the problems in your code and how to fix them like a fellow developer troubleshooting a common input handling snag:

1. Unhandled Newline Trapped in Input Buffer

When you use scanf("%d", &n) to read the element count, the newline character (\n) you press after typing the number stays stuck in the input buffer. The first call to scanf("%c", &tree[i]) will immediately read this newline instead of your first intended element—so your array's first spot gets filled with a blank newline instead of '1' or whatever you entered first.

2. Spaces Get Read as Valid Elements

Your input uses spaces to separate values, but scanf("%c") doesn't skip whitespace. It reads every character it encounters, including those spaces. This means your array will end up with random spaces mixed in with your target elements (like '1', '4', 'x'), which is definitely not what you want.

3. No Safety Check for Malloc Failure

malloc can return NULL if the system runs out of memory to allocate. If you skip checking for this, your program might crash or behave unpredictably when memory allocation fails.


Fixed Code

Here's the corrected version that addresses all these issues:

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

int main() {
    char* tree;
    int n;

    // Read element count with input validation
    if (scanf("%d", &n) != 1) {
        printf("Failed to read number of elements\n");
        return 1;
    }

    // Allocate memory and check for allocation failure
    tree = (char*)malloc(sizeof(char) * n);
    if (tree == NULL) {
        printf("Memory allocation failed—insufficient memory\n");
        return 1;
    }

    // Read elements, automatically skipping whitespace
    for (int i = 0; i < n; i++) {
        // The leading space in "%c" tells scanf to ignore all whitespace (newlines, spaces, tabs)
        if (scanf(" %c", &tree[i]) != 1) {
            printf("Failed to read element at position %d\n", i);
            free(tree); // Clean up allocated memory before exiting
            return 1;
        }
    }

    // Optional: Verify the array content
    printf("Your loaded array: ");
    for (int i = 0; i < n; i++) {
        printf("%c ", tree[i]);
    }
    printf("\n");

    // Always free dynamically allocated memory to avoid leaks
    free(tree);
    return 0;
}

Key fixes breakdown:

  • The leading space in scanf(" %c", &tree[i]) is a simple trick to make scanf skip all whitespace characters before reading the actual element you care about.
  • Added checks for scanf return values: Ensures we don't proceed if input reading fails.
  • Added malloc failure check: Prevents us from using a invalid NULL pointer.
  • Added free(tree): Critical to clean up dynamically allocated memory and avoid memory leaks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:54:12