C++CURL无法设置标头

C++ CURL cannot set header

本文关键字:设置 C++CURL      更新时间:2023-10-16

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

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

上面的代码很好,但如果我把代码改为下面的代码,我发现发送的标头不包含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);

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

问题是将指向chunk的指针传递给函数,然后为其分配不同的值。通过复制传递指针本身,这意味着函数内的h,是一个不同于其外部chunk的指针(是的,它们都指向同一位置,但这无关紧要,因为您更改的是指针本身的值,而不是它指向的内存)。要改变这一点,请通过引用传递指针:

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