二维数组的动态分配 [英] Dynamic Allocation of 2D Array

查看:133
本文介绍了二维数组的动态分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现用邻接矩阵图,但我无法来解决分段错误。谁能帮我指导二维矩阵的动态分配?我也想知道如何存储在内存中的二维数组,它是如何被访问。

 #包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;结构图{
INT伏; //要重新present数顶点...
INTê; //要重新present号边缘.....
INT **调; //二维矩阵,以形成邻接矩阵...
};
结构图形* adjMatrixOfGraph(){        INT I; //用于扫描它们之间的边缘....
        诠释U,V; // for循环,而initliasing邻接矩阵...
        结构图* G =(结构图*)malloc的(的sizeof(结构图)); //        如果(!G){
        的printf(内存错误);
        返回;
        }        的printf(顶点数);        scanf函数(%d个,&安培; G-> V);
        的printf(%d个,G> V);
        输出(边的数量);
        scanf函数(%d个,&安培; G-> E);
        G->调=(INT **)的malloc(sizeof的(G-> V * G-> V)); ADJ); //为G-&GT分配内存;
        / *动态内存分配的二维数组* // * G->调=的malloc(G-> V *的sizeof(INT));
            如果(G->调== NULL){
                 的printf(出内存的\\ n);
                }         对于(i = 0; I< G->伏;我++){
                G->调[I] =的malloc(G-> V *的sizeof(INT));
                如果(G->调[I] == NULL){
                的printf(出内存的\\ n);
                }
                }
* /        如果(!G-> ADJ)
        {
        的printf(内存错误);
        返回;
        }
        对于(U = 0; U< G->伏;ü++){
        为(V = 0; V族G->伏; v ++){
         //的printf(%D,U,V);
         G->调[U] [V] = 0; //完整的邻接矩阵initalising为零。
        }
        }        //输入边缘..和顶点。
        //我们正在考虑这个图作为无向1 ...
        对于(i = 0; I< G-&GT,E,我++)
        {
        scanf函数(读书边%D,&安培; U,&安培; 5);
        G->调[U] [V] = 1;
        G->调[U] [V] = 1;        //如果这个图是导演那么,我们应该有considere只有一面...
        // G-> V [U] [V] = 1;        }
返回G组;
}主要()
{
结构图形* G1 = adjMatrixOfGraph();//结构图形* adjMatrixOfGraph(){
的printf(成功);
返回0;
}


解决方案

分配内存为 INT **调通过以下方式完成:

首先,你对指针的整数数量,您将有分配内存

  =调的malloc(sizeof的为(int *)* number_of_integers); / *通知我传给sizeof的* /

接下来,您对每个单独的整数分配内存:

 为(i = 0; I< number_of_integers;我++)
    形容词[I] =的malloc(sizeof的(INT)* G-> E);

当然每个的malloc 调用需要后跟一个免费调用,以类似的方式。

请注意,我不投的malloc 的结果。

我做了一些其他更改到code:

更新 scanf函数,以确保你有剩余的缓冲区换行没有问题:

 的printf(顶点数:);
    scanf函数(%d个,&安培; G-> V);
    的printf(边数:);
    scanf函数(%d个,&安培; G-> E);

初​​始化它们(可选地,查找释放calloc 时,因为它的零初始化为你):

 的(U = 0; U< G->伏;ü++)//每个顶点
    {
        为(V = 0; V族G-&GT,E; v ++)//每个边缘
        {
            G->调[U] [V] = 0;
        }
    }

下面,我不知道,你手动的边缘设置为1,右边的部分?你不应该使用 G-> V ,而不是 G->的ΔE

 为(i = 0; I< G->伏;我++)
    {
        的printf(读顶点U:);
        scanf函数(%d个,&安培; U);
        的printf(读书边五:);
        scanf函数(%d个,&安培; 5);        如果(U> G-> V || V> G-> E)//简单的错误处理
        {
            的printf(输入比顶点/边缘的\\ n个头大);
            出口(1);
        }        G->调[U] [V] = 1;        G->调[U] [V] = 1;
    }

我能够在此之后,打印成功。如果你想使这个更容易一些,编译code与 -g 标记,如果你在Linux上做的ulimit - ç无限。这将每次你得到一个段错误的时间创建一个核心转储文件。

然后,看看问题出在哪里,运行 GDB your_app核心和内部运行回溯。我不能强调是多么的重要在这些情况下使用调试器。

I am implementing graphs using adjacency matrix, but I am unable to solve the segmentation fault. Can anyone help me in guiding dynamic allocation of two dimensional matrix? I also want to know how is 2-D array stored in memory and how it is accessed.

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

struct Graph{
int V; // To represent number the vertex...
int E; //To represent number the Edge.....
int **Adj; // Two dimensional matrix to form the adjacency matrix... 
};


struct Graph *adjMatrixOfGraph(){

        int i;    //for scanning the edges between them .... 
        int u,v; // for loop while initliasing the  adjacency matrix... 
        struct Graph *G=(struct Graph*) malloc(sizeof(struct Graph)); //

        if(!G){
        printf("Memory Error");
        return;
        }

        printf("Number of Vertices");

        scanf("%d",&G->V);
        printf("%d",G->V);
        printf("Number of Edges");
        scanf("%d",&G->E);
        G->Adj=(int **)malloc(sizeof(G->V * G->V)); //allocating memory for G->Adj);
        /*Dynamic memory allocation for Two Dimensional Arrays */

/*      G->Adj = malloc(G->V * sizeof(int )); 
            if(G->Adj == NULL) {         
                 printf( "out of memory\n");     
                }     

         for(i = 0; i < G->V; i++) {     
                G->Adj[i] = malloc(G->V * sizeof(int ));     
                if(G->Adj[i] == NULL) {         
                printf( "out of memory\n");     


                } 
                }
*/

        if(!G->Adj)
        {
        printf("Memory Error");
        return;
        }


        for(u=0;  u < G->V; u++){
        for(v=0; v < G->V; v++){
         //printf("%d %d",u,v); 
         G->Adj[u][v]=0;  //initalising the complete adjacency matrix to zero.
        }
        }

        //Enter the edges.. and the vertices.
        //We are considering this graph as undirected one ... 
        for(i=0;i< G->E;i++)
        {
        scanf("Reading Edges %d %d ",&u,&v);
        G->Adj[u][v]=1;
        G->Adj[u][v]=1;

        //if this graph was directed then we should have considere only one side... 
        //G->V[u][v]=1;

        }


return G;
}

main()
{
struct Graph *G1=adjMatrixOfGraph();

//struct Graph *adjMatrixOfGraph(){
printf("Successful");
return 0;
}

解决方案

Allocating memory for int **Adj is done in the following way:

First you allocate memory for the number of pointers to integers you will have:

Adj = malloc(sizeof(int*) * number_of_integers); /* notice what I pass to sizeof */

Next you allocate memory for each integer individually:

for (i = 0; i < number_of_integers; i++)
    Adj[i] = malloc(sizeof(int) * G->E);

And of course every malloc call needs to be followed by a free call, in a similar fashion.

Notice I don't cast the result of malloc.

I've made a few other changes to your code:

Update your scanf to ensure you have no problems with newlines remaining in the buffer:

    printf("Number of Vertices: ");
    scanf(" %d", &G->V);
    printf("Number of Edges: ");
    scanf(" %d", &G->E);

Initialise them (alternatively, lookup calloc, as it does zero-initialisation for you):

    for(u=0;  u < G->V; u++) // for each vertice
    {
        for(v=0; v < G->E; v++) // for each edge
        {
            G->Adj[u][v] = 0;
        }
    }

The part below I'm not sure about, you manually set the edges to one, right? Shouldn't you use G->V and not G->E?

    for(i = 0; i < G->V; i++)
    {
        printf("Reading vertice u: ");
        scanf(" %d",&u);
        printf("Reading edge v: ");
        scanf(" %d",&v);

        if (u > G->V || v > G->E) // simple error handling 
        {
            printf("Input bigger than size of vertice/edges\n");
            exit(1);
        }

        G->Adj[u][v] = 1;

        G->Adj[u][v] = 1;
    }

I was able to print Successful after this. If you want to make this a little easier, compile your code with the -g flag and if you're on Linux do ulimit -c unlimited. This will create a coredump file every time you get a segfault.

Then to see where the problem is, run gdb your_app core and inside run backtrace. I cannot stress how important it is to use a debugger in these cases.

这篇关于二维数组的动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆