double pointer to struct inside struct

3.4k views Asked by At

How can i access to a duble pointer in a struct pointer?? with the code bellow, calling addBow() give me a Segmentation fault (core dumped) error

typedef struct
{
    int size;
    tCity **cities;

}tGraph;

//para iniciar el grafo
void initGraph(tGraph *graph, int size)
{
    graph = (tGraph*)malloc(sizeof(tGraph));
    graph->cities = (tCity**)malloc(sizeof(tCity*) * size);
    graph->size = size;
}

//agrega un arco entre ciudades
void addBow(tGraph *graph, int id, tCity *city)
{
    if ( graph->cities[id] == NULL ) 
    {    
        graph->cities[id] = city;
    }
    else
    {
        tCity *cur = graph->cities[id];
        while ( getNext(cur) != NULL ) 
        {
            cur = getNext(cur);
        }
        setNext(cur, city);
    }
}    

which is the correct syntax for graph->cities[id]??

Thanks

SOLUTION: editing the initGraph solve the problem since the memory wasn't allocated

tGraph* initGraph(int size)
{
    tGraph *graph = (tGraph*)malloc(sizeof(tGraph));
    graph->cities = (tCity**)malloc(sizeof(tCity*) * size);
    graph->size = size;
    return graph;
}
4

There are 4 answers

1
Manoj Pandey On BEST ANSWER

You should either have initGraph() take (**graph) or return the graph. Since the malloc address of graph is local to initGraph.

Something like:

void initGraph(tGraph **graph, int size)
{
    tgraph *temp;
    temp = (tGraph*)malloc(sizeof(tGraph*));
    temp->cities = (tCity**)malloc(sizeof(tCity*) * size);
    temp->size = size;
    *graph = temp;
}
1
Scotty Bauer On

graph = (tGraph*)malloc(sizeof(tGraph*));

There is one of your problems... it should be graph = malloc(sizeof(tGraph));

0
verbose On

Make initGraph () return a pointer to tGraph.

tGraph* initGraph(int size) {

tGraph* graph;

graph = malloc(sizeof(tGraph));
graph->cities = malloc(sizeof(tCity*) * size);
graph->size = size;

return graph;
}
1
Abhinav kumar On
//consider this example
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct test{
    int val;    
}test;

typedef struct data{
    char ch[10];
     test **p;
}data;

int main(){
    data *d=malloc(sizeof(data));
    strcpy(d->ch,"hello");
    d->p=(test**)malloc(sizeof(test*));
    d->p[0]=(test*)malloc(sizeof(test));
    d->p[0]->val=10;
    printf("%s,%d",d->ch,d->p[0]->val);
}