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

如何用C语言指针方法设置矩阵值?程序运行异常求助

问题分析与解决

核心问题:参数类型不匹配引发内存访问错误

你的setMatrixValues函数第二个参数声明为int **firstMatrix,但main中传入的是二维数组matrix_1。C语言中,二维数组退化为指针时,是指向一维数组的指针(类型为int (*)[N],N为数组列数),而非int**。这种类型不匹配会导致访问firstMatrix[*pI][*pJ]时触发非法内存访问,程序在循环到第二行时直接崩溃。

修正方案与优化点

  1. 修正函数参数类型,适配二维数组的传入规则
  2. 去除fgets读取内容中的换行符,避免strtok处理异常
  3. 简化循环变量的使用,去掉不必要的指针包装

修正后的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 4

// 清空输入缓冲区
void clearBuffer(void) {
    char input;
    while ((input = getchar()) != '\n' && input != EOF);
}

// 修改参数为指向变长数组的指针,匹配二维数组类型
void setMatrixValues(int *firstMatrixSize, int (*firstMatrix)[*firstMatrixSize]) {
    char temp2[200];
    int i, j;

    printf("First matrix size: %d\n", *firstMatrixSize);

    printf("Input elements of matrix 1: ");
    fgets(temp2, sizeof(temp2), stdin);
    // 去除换行符,避免strtok识别为分隔符
    temp2[strcspn(temp2, "\n")] = '\0';
    char *token = strtok(temp2, " ");

    for(i = 0; i < *firstMatrixSize; ++i) {
        for(j = 0; j < *firstMatrixSize; ++j) {
            printf("I: %d, J: %d\n", i, j);
            printf("Token: %d\n", atoi(token));
            firstMatrix[i][j] = atoi(token);
            printf("Value: %d\n", firstMatrix[i][j]);
            token = strtok(NULL, " ");
        }
    }
}

void setMatrixSize(int *firstMatrixSize, int *secondMatrixSize) {
    char temp[200];
    printf("Input the size: ");
    fgets(temp, sizeof(temp), stdin);
    temp[strcspn(temp, "\n")] = '\0';

    char *token = strtok(temp, " ");

    for(int i = 0; i < 2; i++) {
        if(i == 0) {
            *firstMatrixSize = atoi(token);
        } else {
            *secondMatrixSize = atoi(token);
        }
        token = strtok(NULL, " ");
    }
}

int main(int argc, char *argv[]) {
    int size_matrix_1;
    int size_matrix_2;
    int *pSize_matrix_1 = &size_matrix_1;
    int *pSize_matrix_2 = &size_matrix_2;

    setMatrixSize(pSize_matrix_1, pSize_matrix_2);

    // 变长数组,C99及以上标准支持
    int matrix_1[*pSize_matrix_1][*pSize_matrix_1];
    int matrix_2[*pSize_matrix_2][*pSize_matrix_2];

    printf("Size of matrix 1: %d\n", *pSize_matrix_1);
    setMatrixValues(pSize_matrix_1, matrix_1);

    return 0;
}

关键修改说明

  • 参数类型适配:将setMatrixValues的第二个参数改为int (*firstMatrix)[*firstMatrixSize],这是指向变长数组的指针,完美匹配main中传入的二维变长数组类型,解决内存访问错误。
  • 换行符处理:用strcspn截断fgets读取的换行符,避免strtok将换行符识别为分隔符导致后续token获取异常。
  • 代码简化:直接使用i、j作为循环变量,去掉冗余的指针包装,提升代码可读性。

运行修正后的代码,输入2 2和1 2 3 4,即可完成所有矩阵元素的赋值,输出完整的循环日志。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:27:36