代码之家  ›  专栏  ›  技术社区  ›  Francis M

使用指针创建结构

  •  1
  • Francis M  · 技术社区  · 7 年前

    我正在开发一个程序,该程序创建了一个结构,其中包含用于添加和显示新节点的函数。我有一个名为“add”的函数,我使用它创建新节点并将它们发送到struct->接下来,每当我尝试运行函数“displayData”时,函数都会说我的结构为NULL/空。

    这是代码。

        #include <stdio.h>
        #include <stdlib.h>
    
        typedef struct node *nodePtr;
        struct node {
        int item;
        nodePtr next;
        };
        typedef nodePtr Statistician;
    
        int input();
        Statistician newStatistician();     //allocates memory to the structure.                 Dynamic allocation
        void add(Statistician s, int x);    //Adds data to the rear
        void displayData(Statistician s);   //prints entire dataset
    
        int main() {
    
            int operation, data;
            Statistician s = NULL;
    
            data = input();                 //get new input
            add(s,data);                    //run add function
            displayData(s);                 //run display function
        }
    
        int input(){
            int x;
            printf("Enter data: ");
            if (scanf("%d", &x) != 1)
            {
                printf("\n\nInvalid Input!\n\n");
                exit(0);
            }
            return x;
        }
    
        Statistician newStatistician(){
            Statistician newStat;
            newStat = malloc(sizeof(struct node));
            return newStat;
        }
    
        void add(Statistician s, int x){
            Statistician newNode = newStatistician();
            newNode->item = x;
            newNode->next = NULL;
            if(s == NULL){
                 s = newNode;
                 return;
            }
            while (s != NULL) {
                s = s->next;
            }
            s->next = newNode;  
        }
    
        void displayData(Statistician s){
             Statistician temp = s;
             if(s==NULL){
                printf("\n\nList is EMPTY.");
                printf( "\n\nPress any key.\n" );
                getch();
                return;
             }
            printf( "\n\nThe List:\n" );
            while (temp != NULL) {
                printf(" %d", temp->item);
                temp = temp->next;
            }
    
            printf( "\n\nPress any key.\n" );
            getch();
            return;
        }
    

    使用displayData时,输出为。

           List is EMPTY
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Vlad from Moscow    7 年前

    必须通过引用传递头部节点。否则,更改列表的函数将处理头部节点的副本,并且不会更改原始头部节点。

    例如

    void add(Statistician *s, int x)
    {
        Statistician newNode = newStatistician();
        newNode->item = x;
        newNode->next = NULL;
    
        while ( *s != NULL ) s = &( *s )->next;
    
        *s = newNode;
    }
    

    函数的调用方式如下

    add( &s, data );