【问题标题】:C++ CURL cannot set headerC++ CURL 无法设置标题
【发布时间】:2015-02-16 06:25:41
【问题描述】:

我目前正在开发一个关于 CURL 的程序。我编写了以下代码来添加自定义标题:-

struct curl_slist *chunk = NULL;    
chunk = curl_slist_append(chunk, "Another: yes");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);

上面的代码没问题,但是如果我把代码改成下面的,我发现发送的header中没有Another: yes

void add_header(CURL *c, struct curl_slist *h){
    h = curl_slist_append(h, "Another: yes");
}

struct curl_slist *chunk = NULL;
add_header(curl, chunk);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);

我的第二段代码有什么问题?

【问题讨论】:

    标签: c++ curl


    【解决方案1】:

    问题在于您将指向chunk 的指针传递给函数,然后为其分配不同的值。您正在通过副本传递指针本身,这意味着函数内部的 h 与外部的 chunk 是不同的指针(是的,它们都指向相同的位置,但这没关系,因为您正在更改指针本身的值,而不是它指向的内存)。要更改它,请通过引用传递指针:

    void add_header(CURL *c, struct curl_slist *&h){ //note the *&
        h = curl_slist_append(h, "Another: yes");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多