发送和接收

时间:2019-12-22 13:27:47

标签: c pointers

我有一个任务,必须创建多个队列。目前,我很困惑,因为我不了解如何将消息发送到特定队列以及如何将输入的消息发送/接收到特定队列。这是我编写的代码:

typedef struct _node {
    const char *message;
    struct _node *next;
} node_t;

1 个答案:

答案 0 :(得分:1)

我认为这段代码会产生预期的行为:

typedef struct msg_queue_node {
    char * message;
    struct msg_queue_node * next;
} msg_queue_node_t;


typedef struct msg_queue {
    msg_queue_node_t * head, * tail;
} msg_queue_t;


int main(void)
{
    int i, id;      // indentifies the message queue in the array
    msg_queue_t * msg_queues = malloc(NUM_QUEUES * sizeof(msg_queue_t*));

    for (i = 0; i < NUM_QUEUES; i++)
        msg_queues[i] = createQ();

    // ...

    while ( /*condition*/ ) {

        scanf("%c %d", choice, id);

        switch (choice) {
            case '4':
                printf("\nSending a message\nEnter message to send:");
                scanf("%s", msg);
                sendMessage(msg_queues[id-1], msg);
                break;
            case '5':
                printf("\nReceiving a message\n");
                printf("Message received: %s\n", receiveMessage(msg_queues[id-1]));
                break; 
        }
    }

    // ...
}

msg_queues是大小为NUM_QUEUES的数组。

在我的解决方案中,我们希望用户输入他希望向/从中发送/接收消息的队列的标识符。我假设每个队列的标识符对应于其在数组+ 1中的索引,即标识符为1,...,NUM_QUEUES。