2014-11-18 4 views
0

Я собрал следующий код, используя только примечания из моей лекции, поэтому прошу прощения, если что-то очевидное отсутствует. Я получаю красные подчеркивания под параметрами «Node» newNode (int item, Node * h) `, которые говорят« неспособность разрешить идентификатор ». В основном, этот код пытается добавить новый узел в начало связанного списка. Не могли бы вы рассказать мне, что я делаю неправильно?Попытка понять Связанные списки и структуры

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

struct Node; 
Node *newNode(int item, Node *h); 
/* 
* 
*/ 
int main(int argc, char** argv) { 

    typedef struct node{ 
     int info; 
     struct node *link; 
    }Node; 

    Node *head = NULL; 

    Node *newNode(int item, Node *h){ 

     Node *p; 
     *p = (Node *) malloc(sizeof(Node)); 
     p -> info = item; 
     p -> link = h; 
     return p; 

    } 

    head = newNode(1, head);     //add a new head to start of list 




    return (EXIT_SUCCESS); 
} 

ответ

1

Существует тонкое различие между прямым объявлением структуры и typedef. Он запутывается, потому что его довольно часто игнорируют нотацию структуры и делают только typedefs.

Посмотрите на это:

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

struct node; //We're forward declaring a struct called node (small n). 

//We're declaring a function that accepts node structs (small n). 
struct node *newNode(int item, struct node *h); 

//We are doing two things here. 
//First, we're defining the structure of node (which we forward declared). 
//Second, we're aliasing struct node (small n) as Node (Big N) in a typedef declaration. 
typedef struct node{ 
    int info; 
    struct node *link; 
}Node; 

//From now on (and only now on) we can refer to Node and it will be seen as 
//the same as struct node (small n). 

//Now we define that function we declared above. 
//Notice the declaration used struct node (small n) but this just uses Node (big N). 
//The typedef tells the compiler they mean the same thing! 
Node *newNode(int item, Node *h){ 

    Node *p; 
    p = (Node *) malloc(sizeof(Node)); 
    p -> info = item; 
    p -> link = h; 
    return p; 
} 

//No matter how toy your example we need to clean up after ourselves! 
//It's just good practice. 
//This only frees a single node in isolation but it's enough for your example. 
void deleteNode(Node* n){ 
    free(n); 
} 

int main(int argc, char** argv) { 


    Node *head = NULL; 


    head = newNode(1, head);     //add a new head to start of list 

    //Do something with your lovely new node here. 
    printf("head node value = %d\n",head->info) //The head node value is 1. 

    deleteNode(head); 

    return (EXIT_SUCCESS); 
} 
+0

Чудесно объяснил – user3195991

0

Вы пытаетесь определить функцию внутри другой функции. Это не поддерживается стандартом C.

Вы можете решить эту проблему, переместив определение функции typedef и newNode()main().

0

Вы определяете структуру узла в основной программе, которая не определяется глобально внутри собственной области. Вам нужно будет заменить struct Node; со структурой, определенной в основном:

typedef struct node{ int info; struct node *link; }Node;

Вы также определение функции узла в основном, а затем пытаетесь использовать его, чтобы определить вашу голову или начальный указатель. Ваша программа должна выглядеть следующим образом:

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

typedef struct node{ 
    int info; 
    struct node *link; 
}Node; 

Node *newNode(int item, Node *h); // Function Prototype to new node. 
/* 
* 
*/ 
int main(int argc, char** argv) { 

Node *head = NULL; 

head = newNode(1, &head); //add a new head to start of list // You want to send the reference of the pointer 
                   // to the function newNode. 

return (EXIT_SUCCESS); 
} 

Node *newNode(int item, Node *h){ 

    Node *p; 
    p = (Node *)malloc(sizeof(Node)); // Do not use *p that deferences the pointer that you are trying to allocate memory for. 
    p->info = item; 
    p->link = h; 
    return p; 
} 

Слово предупреждения! Я прошу вас обратиться к своему учебнику или другим учебным сайтам, которые по существу показывают вам, как следует отформатировать программу. Ошибки, вызванные вашим кодом, являются самыми основными, и если вы хотите полностью понять распределение динамической памяти, я бы попросил, чтобы вы начали там, прежде чем продолжить.