在函数内更改指针

标签 c pointers pass-by-reference message-queue

我正在用 C 编写一个消息队列 API,但我在接收方法时遇到了问题。我向消息队列发送一个 char* 消息(“BOB”),它被成功存储。然后我尝试接收消息,但失败了。

在 mq_receive() 内部,正确的消息被出列并且 ret_val->buf 指向 0x012f5754(“BOB”)。接下来,msg_ptr(原本是 0x00000000)被赋值为 0x012f5754。一切都按预期工作,直到程序返回到 main()。在 main() 中,receive_message 仍然是 NULL。我期待它指向 BOB 的第一个字符,即 0x012f5754。我究竟做错了什么?谢谢。

//main.c
main(){
    char* receive_message = NULL;
    //message queue init ...
    mq_send(msq_id, "BOB"); //this works correctly
    mq_receive(msq_id, receive_message);      
    printf("return value: %p\n", receive_message); 
}

//message_queue.c
mqd_t mq_receive(mqd_t mqdes, char *msg_ptr)
{
    queue_t* ret_val;
    q_attr* attr_ptr = (q_attr*)mqdes;
    ret_val = dequeue(attr_ptr);
    //all this works ret_val->buf points to BOB
    msg_ptr = ret_val->buf;
    return mqdes;
}

最佳答案

参数在C中是按值传递的,需要将receive_message的地址传递给mq_receive():

mqd_t mq_receive(mqd_t mqdes, char **msg_ptr)
{
    queue_t* ret_val;
    q_attr* attr_ptr = (q_attr*)mqdes;
    ret_val = dequeue(attr_ptr);
    //all this works ret_val->buf points to BOB
    *msg_ptr = ret_val->buf;
    return mqdes;
}

并调用它:

mq_receive(msq_id, &receive_message);  

关于在函数内更改指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11526233/

相关文章:

c - Arm cortex M7处理器中UART的缓冲深度

c - 如何使用 C 中的指针将数组 (1D) 传递给函数?

c++ - 类继承链和指向每个类的指针

Python 和引用传递。局限性?

c++ - 重载运算符 << 返回 ostream&

c - 如果我已经有权访问系统,那么 system() 函数的用途是什么?

c - execl 命令的 read() 输出并仅使用 write() 系统调用打印它

pointers - 指针的 slice ,当传递给对象时,得到具有其他地址的指针

PHP:如何修复此类型提示错误?

C long unsigned int 的简写形式是什么