Home > OS >  Convert to Pointer Argument in Function (C)
Convert to Pointer Argument in Function (C)

Time:11-21

There is a function that takes the following argument :

int send_message(const char *topic)

I have a struct :

typedef struct mqtt_topic {
    char topic[200];
} mqtt_topic_t;

and a value that is of the type : mqtt_topic_t *mqtt_topic

I am trying to pass mqtt_topic->topic as an argument to the function but it throws an error. How do I convert this data to useful format that I can then use as an argument in my function?

Here is the code snippet :

int mqtt_publish(char message[])
{
    int msg_id = 0;
    ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
    mqtt_topic_t *mqtt_topic = get_mqtt_topic();


    msg_id = esp_mqtt_client_publish(client,&mqtt_topic->topic, message, 0, 1, 0);
    ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
    return msg_id;
}

Function Prototype :

int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain);

CodePudding user response:

The argument &mqtt_topic->topic has type "pointer to char[200]". What you want is pointer to just char:

msg_id = esp_mqtt_client_publish(client, mqtt_topic->topic, message, 0, 1, 0);

When passed as argument, or used in almost any other way except with & and sizeof operators, array decays to pointer to its first element. This is why mqtt_topic->topic gives char*, which is ok as const char* parameter needed here.

CodePudding user response:

you do not need & in front of mqtt_topic->topic.

If your code does not compile (it is giving errors - not warnings) it means that you use a C compiler instead of C compiler or you set warning to be treated as errors.

  •  Tags:  
  • c
  • Related