c - C中两个函数之间的指针

标签 c function pointers

int mqtt_connection()
{
    mqtt_broker_handle_t *broker = mqtt_connect(client_name, ip_addr, port);

    if(broker == 0) {  
    printf("Connection failed, Please check the IP and port of broker\n");  
     return 0;          
        }
    else {
        printf("Connection established successfully\n");
    }
    return 1;
}


int publish_mqtt()
{
    char msg[128] = "Test 2";

    if(mqtt_publish(broker, topic1, msg, QoS1) == -1) 
    {
            printf("publish failed\n");
    }
    else {
        printf("Sent messages\n");
    }
    return(0);
}

我在使用 scons 构建时遇到错误

master.c: In function 'publish_mqtt':
master.c:39:17: error: 'broker' undeclared (first use in this function)
if(mqtt_publish(broker, topic1, msg, QoS1) == -1) 
             ^
master.c:39:17: note: each undeclared identifier is reported only once          for each function it appears in
 scons: *** [master.o] Error 1
  scons: building terminated because of errors.

如何在两个函数之间交换 broker 的值?。还有其他方法可以实现吗?

最佳答案

How to exchange the value of broker between two functions?. Is there any other way to implement this?.

更改两个函数的签名。

  1. 将第一个函数更改为返回 broker
  2. 将第二个函数更改为期望 broker 作为参数。

mqtt_broker_handle_t* mqtt_connection()
{
   mqtt_broker_handle_t *broker = mqtt_connect(client_name, ip_addr, port);

   if(broker == 0)
   {
      printf("Connection failed, Please check the IP and port of broker\n");  
      return NULL;          
   }
   else
   {
      printf("Connection established successfully\n");
      return broker;
   }
}


int publish_mqtt(mqtt_broker_handle_t* broker)
{
   char msg[128] = "Test 2";

   if(mqtt_publish(broker, topic1, msg, QoS1) == -1) 
   {
      printf("publish failed\n");
   }
   else
   {
      printf("Sent messages\n");
   }
   return(0);
}

更改调用函数。

mqtt_broker_handle_t* broker = mqtt_connection();
publish_mqtt(broker);

关于c - C中两个函数之间的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157137/

相关文章:

作为函数的变量的 Python 命名约定

vector 中不存在 C++ 字符串成员变量

c - 关于Linux内核中的NAPI实现

c - sigkill 不会终止 C 程序

c++ - 有关使用return的C++函数

c - 为什么 fputs() 需要一个常量作为第一个参数而不是 fputc()?

代码无法找到最大总和

c++ - 如果我使用 scanf 程序终止

c++ - 删除指针: delete/delete[]/free?的方法

c - (size_t)((char *)0) 的计算结果是否为 0?