【问题标题】:Issue with Adjacency List in CC中的邻接表问题
【发布时间】:2014-11-24 22:46:15
【问题描述】:

我正在尝试使用邻接列表在图中插入节点,但是当我尝试插入此行时它会崩溃

criaEstacao("Edgware Road", "Verde, Rosa", 200, 0);

在 main() 上。如果只有一个插入它可以工作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 20
#define TRUE 1
#define FALSE 0


typedef struct no{
    char nome[100];
    char linhas[100];
    int distancia;
    int manutencao;
    struct no *prox;
    struct no *ant;
} No;

No *LinhaAmarela[max];

No *criaEstacao(char n[100], char l[100], int d, int m){
    int i = 0;
    No *novo = (No*)malloc(sizeof(No*));

    strcpy(novo->nome, n);
    strcpy(novo->linhas, l);
    novo->distancia = d;
    novo->manutencao = m;
    novo->prox = NULL;
    novo->ant = NULL;

    while (LinhaAmarela[i] != NULL && i < max){
        i++;
    }

    LinhaAmarela[i] = novo;
}

int main() {
    criaEstacao("Paddington", "Verde, Rosa, Marrom", 200, 0);
    criaEstacao("Edgware Road", "Verde, Rosa", 200, 0);

    getch();
}

【问题讨论】:

    标签: c


    【解决方案1】:

    为结构分配内存,而不是指针:

    No *novo = malloc(sizeof(No));
    

    更好的:

    No *novo = malloc(sizeof(*novo));   
    

    并始终检查返回值。

    【讨论】:

      猜你喜欢
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 2012-12-09
      相关资源
      最近更新 更多