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

C语言如何实现一行内动态数量输入及二维数组动态输入?

实现C语言中任意数量的单行输入与动态二维数组输入

一、单行任意数量整数的动态输入

要处理一行中任意数量的整数输入,核心思路是动态扩容内存:先分配初始大小的数组,读取过程中如果内存不足就重新分配更大的空间,直到读取到换行符或输入结束。

代码实现

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

int* read_dynamic_line(int *count) {
    int capacity = 4; // 初始容量
    int *arr = malloc(capacity * sizeof(int));
    if (!arr) {
        perror("malloc failed");
        exit(EXIT_FAILURE);
    }

    *count = 0;
    int num;
    // 读取整数,直到遇到换行或EOF
    while (scanf("%d", &num) == 1) {
        // 检查是否需要扩容
        if (*count >= capacity) {
            capacity *= 2;
            int *temp = realloc(arr, capacity * sizeof(int));
            if (!temp) {
                perror("realloc failed");
                free(arr);
                exit(EXIT_FAILURE);
            }
            arr = temp;
        }
        arr[(*count)++] = num;

        // 检查当前输入后是否是换行,若则终止循环
        char c;
        while ((c = getchar()) == ' '); // 跳过剩余空格
        if (c == '\n' || c == EOF) {
            ungetc(c, stdin); // 把换行/EOF放回输入流,不影响后续读取
            break;
        } else {
            ungetc(c, stdin); // 把非换行的字符放回,继续读下一个整数
        }
    }

    // 可选:缩容到实际使用的大小,节省内存
    int *final_arr = realloc(arr, (*count) * sizeof(int));
    if (final_arr) {
        arr = final_arr;
    }
    return arr;
}

// 测试单行输入
int main() {
    int count;
    int *nums = read_dynamic_line(&count);

    printf("读取到%d个整数:", count);
    for (int i = 0; i < count; i++) {
        printf("%d ", nums[i]);
    }
    printf("\n");

    free(nums);
    return 0;
}

关键点说明

  • 用malloc初始化数组,realloc动态扩容,每次容量翻倍保证效率;
  • 通过scanf("%d")读取整数,配合getchar()检查换行符,确保只读取当前行的内容;
  • 最后可以用realloc缩容,避免内存浪费;
  • 必须检查malloc和realloc的返回值,处理内存分配失败的情况。

二、动态二维数组的输入(指定行列数)

针对需求中先输入行数、列数,再逐行输入对应数量整数的场景,可结合固定列数读取逻辑实现:

代码实现

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

// 读取指定列数的一行整数
int* read_fixed_columns_line(int cols) {
    int *row = malloc(cols * sizeof(int));
    if (!row) {
        perror("malloc failed");
        exit(EXIT_FAILURE);
    }

    // 读取cols个整数
    for (int i = 0; i < cols; i++) {
        if (scanf("%d", &row[i]) != 1) {
            perror("read integer failed");
            free(row);
            exit(EXIT_FAILURE);
        }
    }

    // 跳过当前行剩余的输入(如果有的话)
    char c;
    while ((c = getchar()) != '\n' && c != EOF);
    return row;
}

int main() {
    int rows, cols;
    // 读取行数和列数
    printf("输入行数:");
    if (scanf("%d", &rows) != 1 || rows <= 0) {
        printf("无效的行数\n");
        return EXIT_FAILURE;
    }
    printf("输入列数:");
    if (scanf("%d", &cols) != 1 || cols <= 0) {
        printf("无效的列数\n");
        return EXIT_FAILURE;
    }

    // 分配二维数组(指针数组形式)
    int **matrix = malloc(rows * sizeof(int*));
    if (!matrix) {
        perror("malloc matrix failed");
        exit(EXIT_FAILURE);
    }

    // 逐行读取数据
    printf("输入%d行,每行%d个整数:\n", rows, cols);
    for (int i = 0; i < rows; i++) {
        matrix[i] = read_fixed_columns_line(cols);
    }

    // 打印验证
    printf("\n你输入的二维数组:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    // 释放内存
    for (int i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);
    return 0;
}

关键点说明

  • 用指针数组实现二维数组,每行独立分配内存,灵活且易释放;
  • 读取行列数时做合法性检查,避免无效输入;
  • 每行读取指定数量的整数后,跳过该行剩余的字符(比如多余的空格或换行),防止影响下一行读取;
  • 内存释放要逐层进行:先释放每行的数组,再释放指针数组。

扩展:每行任意数量的动态二维数组

如果需要每行的整数数量不固定,直接复用单行动态输入函数即可:

// 省略read_dynamic_line函数,同第一个示例

int main() {
    int rows;
    printf("输入行数:");
    if (scanf("%d", &rows) != 1 || rows <= 0) {
        printf("无效的行数\n");
        return EXIT_FAILURE;
    }

    // 分配指针数组,同时存储每行的元素个数
    int **matrix = malloc(rows * sizeof(int*));
    int *col_counts = malloc(rows * sizeof(int));
    if (!matrix || !col_counts) {
        perror("malloc failed");
        exit(EXIT_FAILURE);
    }

    // 跳过行数后的换行
    char c;
    while ((c = getchar()) != '\n' && c != EOF);

    // 逐行读取
    printf("输入%d行任意数量的整数:\n", rows);
    for (int i = 0; i < rows; i++) {
        matrix[i] = read_dynamic_line(&col_counts[i]);
    }

    // 打印验证
    printf("\n你输入的动态二维数组:\n");
    for (int i = 0; i < rows; i++) {
        printf("第%d行(%d个元素):", i+1, col_counts[i]);
        for (int j = 0; j < col_counts[i]; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    // 释放内存
    for (int i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);
    free(col_counts);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:35:27