指向struct里面的struct的双指针

时间:2013-08-31 21:56:36

标签: c struct double-pointer

如何访问struct指针中的duble指针? 使用代码bellow,调用addBow()给我一个Segmentation fault(core dumped)错误

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);
    }
}    

这是graph-> cities [id] ??

的正确语法

由于

解: 编辑initGraph解决了问题,因为没有分配内存

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

4 个答案:

答案 0 :(得分:1)

您应该使用initGraph()获取(**图形)或返回图形。由于graph的malloc地址是initGraph的本地地址。

类似的东西:

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 :(得分:1)

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

你有一个问题...... 它应该是 graph = malloc(sizeof(tGraph));

答案 2 :(得分:0)

initGraph ()返回指向tGraph的指针。

tGraph* initGraph(int size) {

tGraph* graph;

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

return graph;
}

答案 3 :(得分:-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);
}