邮件被覆盖-C

时间:2019-12-26 14:43:48

标签: c function message-queue

我具有以下两个功能,即SendMessage和ReceiveMessage,顾名思义,它们将消息发送到队列并从队列接收消息。我的问题是,接收到的每条消息都被最后输入的元素覆盖。例如-输入的消息将是b c,输出的消息将是c c c。

typedef struct{
    int front, rear;
    char* elements[MAX_MESSAGES];
}queue;


int main(){
    char choice;
    char element[MAX_MSG_LEN];

    queue q;
    create(&q);

    while(1){
        printf("\n1) Send Message");
        printf("\n2) Receive Message");
        printf("\n0) Quit");
        printf("\nEnter choice:");
        scanf(" %c", &choice);

        switch(choice)
        {
            case '1':              
                    printf("\nEnter message to send:");
                    scanf("%s", element);
                    sendMessage(&q, element);                
                break;
            case '2':
                    receiveMessage(&q);              
                break;              
            case '0':
                printf("\nQuitting");
                exit(1);
            default:
                printf("Incorrect. Re-enter.\n");
                break;
        }
    }
}

void create(queue *pq){
    pq -> front = pq->rear = -1;
}

void sendMessage(queue *pq, char element[MAX_MSG_LEN]){
    int i;

    if(pq -> front == -1)
        pq -> front = pq -> rear = 0;

    else if (pq -> rear == MAX_MESSAGES - 1){
        for(i = pq -> front; i <= pq -> rear; i++)
            pq -> elements[i-pq -> front] = pq -> elements[i];

        pq -> rear = pq -> rear + pq -> front -1;
        pq -> front = 0;
    }
    else pq -> rear++;

    pq -> elements[pq->rear] = element;
}

void receiveMessage(queue *pq){
    char* temp;

    temp = pq -> elements[pq -> front];

    if(pq -> front == pq -> rear)
        pq -> front = pq -> rear = -1;
    else
        pq -> front++;

    printf("\nReceived message is %s\n", temp);
}

1 个答案:

答案 0 :(得分:1)

您需要使用barryvdh/laravel-debugbar函数,而不仅仅是传递指针。当您写strcpy时,您只是在复制一个指针值。当您调用pq -> elements[i-pq -> front] = pq -> elements[i];函数并为其指定地址scanf时,您将覆盖指针指向的数组。所有指向该数组的指针都将指向被覆盖的字符数组。

为避免这种情况,请使用element函数将指针指向的数组的值复制到新的数组中,如下所示:

strcpy

对于在strcpy(pq -> elements[i-pq -> front], pq -> elements[i]); //pq -> elements[i-pq -> front] = pq -> elements[i]; elements函数中从sendMessage数组分配一个值的每个实例执行此操作。

还可以通过以下代码修复细分错误。 receiveMessagepq -> front时会发生什么?

-1