-2

我正在开发一个客户端-服务器程序,我何时尝试使用此结构实现用户链表:

typedef struct user {
    char username[50];
    int user_pid;
    struct user *next;
} 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++;
}

主要功能(短版)

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不会更改。这是一个解决方案。从 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. AddUser捕获in的返回值main。而不仅仅是

    AddUser(head, req);
    

    利用

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