2015-11-14 3 views
-1

Я понимаю, что этот вопрос был объяснен много, но на самом деле я отчаянно от своего кода. Я хочу, чтобы создать связанный список, создать 5 новых узлов и добавить их в конце списка по одному:Проблема при создании связанного списка и добавлении к нему узлов

typedef struct msg *M; 
struct msg{ 
    double data; 
    M next; 
}; 

void create_msg(); 
void add(); 

void main(){ 
    srand(0); 
    M list_of_msg = NULL; 
    for(int i = 0; i < 5; i++){ 
     create_msg(list_of_msg); 
     add(list_of_msg , rand()%15); 
    } 

} 

void create_msg(M head){ 
    M m; 
    m = (M)malloc(sizeof(struct msg)); 

    if(head == NULL) 
    { 
     head = m; 
     head->next = NULL; 
    } 
    else 
    { 
     m->next= head; 
     head = m; 
    } 
    return(m); 

} 

void add(M head, double d){ 

    M m, last; 
    m = (M)malloc(sizeof(struct msg)); 
    last = head; 

    m->data = d; 
    m->next = NULL; 

    if (head == NULL) 
    { 
     head = m; 
    } 
    else 
    { 
     while (last->next != NULL) 
     { 
      last = last->next; 
     } 
     last->next = m; 
    } 
} 

Программа не работает, и я не знаю, где это проблема, хотя я проверил построчно. Любые намеки приветствуются.

+0

"Моя программа не работает" далеко от того, чтобы быть ** ** описание конкретных проблем. – Olaf

+0

Отладчик ............. DCV –

ответ

1

вопросы

  • недостающие STDLIB включают таНос прототип
  • функция добавить закодирована для обработки нулевых параметров сообщения, create_msg не надо (и дублирует код в оных)
  • надстройку и прототипы create_msg, несовместимые с определениями функций ниже
  • void main не является одним из стандартных основных прототипов
  • create_msg объявлен недействительным, но возвращает значение
  • функции дополнения (и create_msg) попытку модифицировать свой параметр M вход (который является только локальной копией)
  • ошибок нет проверки после таНоса
  • нет необходимости в отливать void * возвращения таНоса
  • объявляя целое число в течение заголовка цикла уменьшает портативность
  • память сообщений не протекает (не так, чтобы освободить память)
  • у вас нет никакой возможности напечатать список ссылок, чтобы знать, если это работает ред ..

код

#include <stdio.h> 
#include <stdlib.h> 

typedef struct msg *M; 
struct msg{ 
    double data; 
    M next; 
}; 

#define create_msg(M) 
void add(M *head, double d); 
void print_messages(M head); 
void free_messages(M head); 

int main(void){ 
    srand(0); 
    M list_of_msg = NULL; 
    int i; 
    create_msg(list_of_msg); 
    for(i = 0; i < 5; i++){ 
/* create_msg function was redundant and removed to a noop */ 
/* create_msg(list_of_msg);*/ 
    add(&list_of_msg , rand()%15); 
    } 

    print_messages(list_of_msg); 
    free_messages(list_of_msg); 
    return 0; 
} 

void add(M *head, double d){ 

    M m, last; 
    m = malloc(sizeof(struct msg)); 
    if(!m) 
    { 
    /* consider making add return int 
    * this way can throw an error code and check for it from client */ 
    return ; 
    } 
    last = *head; 

    m->data = d; 
    m->next = NULL; 

    if (*head == NULL) 
    { 
    *head = m; 
    } 
    else 
    { 
    while (last->next != NULL) 
    { 
     last = last->next; 
    } 
    last->next = m; 
    } 
} 

void print_messages(M head) 
{ 
    M cursor = head; 
    while(cursor) 
    { 
    printf("%lf ->\n", cursor->data); 
    cursor = cursor->next; 
    } 
} 

void free_messages(M head) 
{ 
    M cursor, next; 
    cursor = head; 
    while(cursor) 
    { 
    next = cursor->next; 
    free(cursor); 
    cursor = next; 
    } 
} 

выход

$ gcc -g test.c -o test 
$ valgrind ./test 
==1121== Memcheck, a memory error detector 
==1121== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. 
==1121== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info 
==1121== Command: ./test 
==1121== 
13.000000 -> 
1.000000 -> 
12.000000 -> 
10.000000 -> 
8.000000 -> 
==1121== 
==1121== HEAP SUMMARY: 
==1121==  in use at exit: 0 bytes in 0 blocks 
==1121== total heap usage: 5 allocs, 5 frees, 80 bytes allocated 
==1121== 
==1121== All heap blocks were freed -- no leaks are possible 
==1121== 
==1121== For counts of detected and suppressed errors, rerun with: -v 
==1121== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) 

ссылка

+0

Большое спасибо. – Mike