2

使用 为二维数组分配内存malloc()时,当输入大小(矩阵 N*N)大于5(即N>5)时会发生分段错误。

以下代码适用于小于 的输入(N)5

你能帮我解决这个问题吗?

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

int main(){
    int n;
    int i,j;
    int **adj;
    //reading size of a N*N matrix
    scanf("%d",&n);

    //dynamically allocating memory for a 2-dimensional array
    adj=(int**)malloc(sizeof(int)*n);
    for(i=0;i<n;i++){
        adj[i]=(int*)malloc(sizeof(int)*n);
    }

    //taking input from the file        
    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            scanf("%d",&adj[i][j]);
        }
    }

    for(i=0;i<n;i++){
        for(j=0;j<n;j++){
            printf("%d\t",adj[i][j]);
        }
        printf("\n");
    }
    return 0;
}
4

3 回答 3

2

这是不正确的:

adj=(int**)malloc(sizeof(int)*n);

当你分配一个数组时int*,不是int。改成:

adj = malloc(sizeof(int*)*n); /* Cast unnecessary. */
/* or: adj = malloc(sizeof(*adj)*n); */

建议检查返回值scanf()以确保int正确读取:

if (1 == scanf("%d", &n))
{
}

有用的阅读:我要转换 malloc 的结果吗?

于 2012-09-25T09:01:39.403 回答
0
adj=(int**)malloc(sizeof(int)*n);

将此替换为

adj = (int**)malloc(sizeof(int*) * n);

因为一般sizeof(int*) != sizeof(int)

另一个提示:初始化你的变量!!!

于 2012-09-25T09:04:07.483 回答
0

除了 hmjd 指向的内容之外,也许它可能提供更多信息。

int p -> p 是 int 类型。

int * p -> p 是指向“int”的指针 (*p) 类型

int ** p -> p 是指针 (*p) 类型,指向“指向 int 的指针,即:(int *)”

如果是从左往右读,会更容易理解。

int ** adj -> 你需要两个指针解引用(**)才能达到值'int'。

即:“adj”指向的内存数组中的每个位置都应该保存另一块内存的地址。因此,您需要在分配“adj”时提供 sizeof(int *)。

于 2012-09-25T09:18:29.690 回答