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

矩阵相加程序故障求助:变量未声明、异常及代码精简建议

Matrix Addition Program Troubleshooting & Optimization

Hey there! Let's work through your matrix addition program issues one by one, plus give you some practical tips to clean up and improve the code.

1. Fixing the "array1 undeclared" Compile Error

This error happens because you’re trying to use array1 (and presumably array2/resultArray) without declaring them first—C requires all variables (including arrays) to be defined before they’re used. Since your matrix dimensions (a for rows, b for columns) come from user input, you have two solid options:

  • Option 1: C99 Variable-Length Arrays (VLAs)
    VLAs let you create arrays with variable sizes (supported by most modern compilers):
    // After reading a and b from the user
    int array1[a][b];
    int array2[a][b];
    int result[a][b];
    
  • Option 2: Dynamic Memory Allocation (More Portable)
    For better compatibility with older compilers, use malloc to allocate memory dynamically:
    int **array1 = malloc(a * sizeof(int *));
    for (int i = 0; i < a; i++) {
        array1[i] = malloc(b * sizeof(int));
    }
    // Repeat the same allocation for array2 and result
    
    Don’t forget to free the memory with free() at the end to avoid memory leaks!

2. Fixing the Program Crash When Removing Print Logic

If the program stops running after removing the sum print section, the issue is likely tied to invalid memory access or unhandled input errors:

  • Check Your scanf Calls
    Your code snippet cuts off at scanf("%d",&...—make sure you’re correctly reading the column value into &b, like:
    scanf("%d", &b);
    
    Always verify scanf’s return value to catch invalid input:
    if (scanf("%d", &a) != 1) {
        printf("Invalid input for rows!\n");
        return 1;
    }
    
  • Ditch Global Variables
    Your a, b, i, j are declared globally. While not directly causing the crash, global variables can lead to unexpected behavior. Move them inside main() instead.
  • Follow C Standards for main
    The C standard requires main to return an int. Change main() to int main() and add return 0; at the end to properly exit the program.

3. Code Simplification & Best Practices

Here’s a cleaned-up, working version of your program with all fixes applied:

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

// Helper function to read matrix values
void readMatrix(int **matrix, int rows, int cols) {
    printf("Enter matrix elements:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
}

// Helper function to add two matrices
void addMatrices(int **a, int **b, int **result, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[i][j] = a[i][j] + b[i][j];
        }
    }
}

// Helper function to print a matrix
void printMatrix(int **matrix, int rows, int cols) {
    printf("Resulting matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int rows, cols;

    // Get and validate matrix dimensions
    printf("Enter number of rows: ");
    if (scanf("%d", &rows) != 1 || rows <= 0) {
        printf("Invalid row count!\n");
        return 1;
    }

    printf("Enter number of columns: ");
    if (scanf("%d", &cols) != 1 || cols <= 0) {
        printf("Invalid column count!\n");
        return 1;
    }

    // Allocate memory for matrices
    int **matrix1 = malloc(rows * sizeof(int *));
    int **matrix2 = malloc(rows * sizeof(int *));
    int **result = malloc(rows * sizeof(int *));
    for (int i = 0; i < rows; i++) {
        matrix1[i] = malloc(cols * sizeof(int));
        matrix2[i] = malloc(cols * sizeof(int));
        result[i] = malloc(cols * sizeof(int));
    }

    // Execute matrix operations
    readMatrix(matrix1, rows, cols);
    readMatrix(matrix2, rows, cols);
    addMatrices(matrix1, matrix2, result, rows, cols);
    printMatrix(result, rows, cols);

    // Free allocated memory
    for (int i = 0; i < rows; i++) {
        free(matrix1[i]);
        free(matrix2[i]);
        free(result[i]);
    }
    free(matrix1);
    free(matrix2);
    free(result);

    return 0;
}

Key improvements here:

  • No global variables (all variables are scoped to where they’re used)
  • Modular functions for better readability and reusability
  • Input validation to prevent crashes from bad user input
  • Proper dynamic memory management to avoid leaks
  • Full compliance with C standards

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:20:55