Dynamic Allocation of 2D Array

夙愿已清 提交于 2019-12-08 18:10:32
Nobilis

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.

int **allocate_2D_array(int rows, int columns)
{
    int k = 0;
    int **array = malloc(rows * sizeof (int *) );

    array[0] = malloc(columns * rows * sizeof (int) );
    for (k=1; k < rows; k++)
    {
        array[k] = array[0] + columns*k;
        bzero(array[k], columns * sizeof (int) );
    }

    bzero(array[0], columns * sizeof (int) );

    return array;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!