1

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

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

4 回答 4

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;
}
于 2013-08-31T22:03:12.247 回答
1

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

你的问题之一......应该是 graph = malloc(sizeof(tGraph));

于 2013-08-31T22:05:07.270 回答
0

使initGraph ()返回一个指向tGraph.

tGraph* initGraph(int size) {

tGraph* graph;

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

return graph;
}
于 2013-08-31T22:40:48.910 回答
-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);
}
于 2020-09-03T08:27:25.037 回答