-2

私はクライアントサーバープログラムを開発しており、いつ、次の構造を使用してユーザーリンクリストを実装しようとしています:

typedef struct user {
    char username[50];
    int user_pid;
    struct user *next;
} user_list;

コンパイラはエラーを出さないので、コードの何が問題なのかを突き止めようとしていますが、ユーザーリストを印刷しようとすると、何も表示されません。

AddUser 関数:

AddUser(user_list *head, req req)
{
    if(head == NULL)
    {
        head = malloc(sizeof(user_list));

        if (head == NULL) 
            fprintf(stdout,"[SERVER] Error memory allocation ");

        strcpy(head->username, req.str);
        head->user_pid = req.client_pid;
        head->next = NULL;
    }
    else
    {   
        user_list *current = head;

        while (current->next != NULL) 
            current = current->next;

        current->next = malloc(sizeof(user_list));
        strcpy(current->next->username, req.str);
        current->next->user_pid = req.client_pid;
        current->next->next = NULL;
    }
    num_users++;
}

主な機能(ショートバージョン)

int Main()
{
struct request req;
struct answer ans;
user_list *head = NULL;

do{

    read(fifo_1, &req, sizeof(req)); // Read client request

    if(strcasecmp(req.str, "adduser") == 0) 
    {               
        AddUser(head, req);
        strcpy(ans.str, "User added with success! You're logged!");
    }

    if(strcasecmp(req.str, "users") == 0) // Print on the screen the users list
    {
        user_list *current = head;

        while (current != NULL) 
        {
            fprintf(stdout, "%s\n", current->username);
            fprintf(stdout, "%d\n", current->user_pid);
            current = current->next;
        }

    }
}while(strcmp(req.str,"exit") != 0);
}
4

1 に答える 1

1

コメントで他の人がすでに指摘していることをまとめます。

  1. 変更しmainます。それ以外の

    int Main()
    

    使用する

    int main()
    
  2. の値をに変更しても、 の値は変更されheadません。これが1つの解決策です。AddUser から戻ります。mainAddUserhead

    user_list* AddUser(user_list *head, req req)
    {
        if(head == NULL)
        {
            head = malloc(sizeof(user_list));
    
            if (head == NULL) 
                fprintf(stdout,"[SERVER] Error memory allocation ");
    
            strcpy(head->username, req.str);
            head->user_pid = req.client_pid;
            head->next = NULL;
        }
        else
        {   
            user_list *current = head;
    
            while (current->next != NULL) 
                current = current->next;
    
            current->next = malloc(sizeof(user_list));
            strcpy(current->next->username, req.str);
            current->next->user_pid = req.client_pid;
            current->next->next = NULL;
        }
        num_users++;
        return head;
    }
    
  3. AddUserinの戻り値をキャプチャしmainます。ただの代わりに

    AddUser(head, req);
    

    使用する

    head = AddUser(head, req);
    
于 2014-09-05T18:33:11.930 に答える