简体   繁体   English

动态分配的二维数组

[英]Dynamically allocated 2d array

I'm trying to create a 2d array, specifically an adjacency matrix for directed graphs. 我正在尝试创建一个2d数组,特别是有向图的邻接矩阵。 I've never tried this with dynamic memory allocation before and I've hit a snag. 我之前从未尝试过使用动态内存分配,而且遇到了麻烦。 Here's the code: 这是代码:

int n, i;
printf("Number of nodes is: ");
scanf("%d", &n);

int ** array = malloc(n * sizeof(int*));
for(i = 0; i < n; i++)
    array[i] = malloc(n * sizeof(int));

printf("Number of edges is: ");
scanf("%d", &m);

int x, y;
for(i=0;i<m;i++)
{
    scanf("%d %d", &x, &y);
    array[x][y]=1;
}

As soon as I finish entering all the edges, the program stops working and throws the usual "exe has stopped working". 当我完成所有输入后,程序将停止工作并抛出通常的“ exe停止工作”。

Where's the problem? 哪里出问题了?

EDIT: houssam spotted my error. 编辑:侯萨姆发现了我的错误。 The first "for" should have gone from 1 to n. 第一个“ for”应该从1变为n。 When I entered 1 6 as an edge, the program crashed because there were only nodes 0-5. 当我输入1 6作为边时,程序崩溃,因为只有0-5个节点。 Thanks for spotting that. 感谢您发现这一点。 Such a simple mistake..... 这么简单的错误.....

you may entered wrong values for x or y , their values should be less than n and greater than or equal to 0 : 您可能为xy输入了错误的值,它们的值应小于n且大于或等于0

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

int main()
{
    int m ,n, i;
    printf("Number of nodes is: ");
    scanf("%d", &n);

    int ** array = malloc(n * sizeof(int*));
    for(i = 0; i < n; i++)
        array[i] = malloc(n * sizeof(int));

    printf("Number of edges is: ");
    scanf("%d", &m);

    int x, y;
    for(i=0;i<m;i++)
    {
        scanf("%d %d", &x, &y);
        if (x >=0 && y >= 0 && x < n && y < n) // here
            array[x][y]=1;
        else
            printf("error in your values x=%d y=%d\n" , x , y);
    }
    return 0;
}

EDIT #1: 编辑#1:
based on comment from user : M Oehm to check the return value of scanf , see: 根据用户: M Oehm的评论检查scanf的返回值,请参阅:
scanf fails why? scanf为何失败? , I can refactor the code to be like: ,我可以将代码重构为:

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

int main()
{
    int m ,n, i;
    printf("Number of nodes is: ");
    scanf("%d", &n);

    int ** array = malloc(n * sizeof(int*));
    for(i = 0; i < n; i++)
        array[i] = malloc(n * sizeof(int));

    printf("Number of edges is: ");
    scanf("%d", &m);

    int x, y;
    for(i=0;i<m;i++)
    {
        //int num_read = scanf("%d %d", &x, &y);
        if(scanf("%d %d", &x, &y) < 2)
        {
            printf("please enter valid two integers..\n");          
            while (getchar() != '\n'); // read all characters in the input stream.
        }
        else if (x >=0 && y >= 0 && x < n && y < n) // here
        {
            array[x][y]=1;
            printf("array[%d][%d]=1;\n" , x, y);

        }
        else
            printf("error in your values x=%d y=%d\n" , x , y);
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM