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

动态读取矩阵时程序崩溃,scanf行触发访问违规如何解决?

问题分析与解决:Access violation writing location 错误

核心错误点

  1. 变量类型声明错误:main函数里你把a声明为int类型,却强制转换为int**使用,这直接导致指针指向的地址完全非法,是崩溃的主要原因。
  2. 内存分配与指针类型不匹配:int**是指向指针的指针,需要先分配n个int*类型的指针数组,再为每个指针分配n个int的存储空间;而你直接用malloc(n*n * sizeof(int))分配了一块连续的int数组,无法被int**正确解析。

另外你怀疑的*(a + i) + j写法本身是正确的,它等价于&a[i][j],问题不在这个表达式上。


修复方案

方案1:正确使用int**类型分配内存

修改main函数的变量声明和内存分配逻辑:

int n,opt;
int** a; // 正确声明为int**类型
printf("number of lines and columns:");
scanf("%d", &n);

// 第一步:分配n个int*指针的空间
a = (int**)malloc(n * sizeof(int*));
if (a == NULL) {
    // 内存分配失败的处理逻辑
    perror("malloc failed");
    return 1;
}

// 第二步:为每个指针分配n个int的存储空间
for (int i = 0; i < n; i++) {
    a[i] = (int*)malloc(n * sizeof(int));
    if (a[i] == NULL) {
        perror("malloc failed");
        // 中途分配失败时释放已分配内存避免泄漏
        for (int k = 0; k < i; k++) {
            free(a[k]);
        }
        free(a);
        return 1;
    }
}

此时你的read和show函数不需要修改,因为*(a + i) + j的写法是正确的。

方案2:用一维数组模拟二维访问(更简洁)

如果不需要多级指针,可以改用一维数组,通过计算索引实现二维访问,内存分配更简单:

// 修改main函数
int n,opt;
int* a;
printf("number of lines and columns:");
scanf("%d", &n);

a = (int*)malloc(n * n * sizeof(int));
if (a == NULL) {
    perror("malloc failed");
    return 1;
}

同时修改read和show函数的参数和访问逻辑:

void read(int *a, int n)
{
    int i, j;
    for(i=0;i<n;i++)
        for (j = 0; j < n; j++)
        {
            printf("a[%d][%d]=", i, j);
            scanf("%d", a + i*n + j); // 用一维索引模拟二维地址
        }
}

void show(int* a, int n)
{
    int i, j;
    for (i = 0; i < n; i++){
        for (j = 0; j < n; j++)
        {
            printf("%d ", a[i*n + j]);
        }
        printf("\n"); // 每行结束换行,更易读
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:35:24