指向struct内部的struct的双指针 [英] double pointer to struct inside struct

查看:116
本文介绍了指向struct内部的struct的双指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问结构指针中的双重指针? 使用下面的代码,调用addBow()会给我一个Segmentation Fault(核心转储)错误

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

这是graph-> cities [id] ??

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

谢谢

解决方案: 编辑initGraph解决了该问题,因为未分配内存

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

推荐答案

您应该让initGraph()接受(**图形)或返回图形.由于图的malloc地址是initGraph的本地地址.

You should either have initGraph() take (**graph) or return the graph. Since the malloc address of graph is local to 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;
}

这篇关于指向struct内部的struct的双指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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