Reputation: 319
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;
}
Upvotes: 1
Views: 3409
Reputation: 1
//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);
}
Upvotes: -1
Reputation: 7917
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;
}
Upvotes: 0
Reputation: 4666
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;
}
Upvotes: 1
Reputation: 1277
graph = (tGraph*)malloc(sizeof(tGraph*));
There is one of your problems...
it should be
graph = malloc(sizeof(tGraph));
Upvotes: 1