簡體   English   中英

有人可以向我解釋這段代碼嗎?

[英]Can someone explain this piece of code to me?

這是我試圖理解但由於指針而無法理解的程序的一小段。

/* issue JSON-RPC request */
val = json_rpc_call(curl, srv.rpc_url, srv.rpc_userpass, s);
if (!val) {
    fprintf(stderr, "submit_work json_rpc_call failed\n");
    goto out;
}

*json_result = json_is_true(json_object_get(val, "result"));
rc = true;

sharelog(remote_host, auth_user,
     srv.easy_target ? "Y" : *json_result ? "Y" : "N",
     *json_result ? "Y" : "N", NULL, hexstr);

if (debugging > 1)
    applog(LOG_INFO, "[%s] PROOF-OF-WORK submitted upstream.  "
           "Result: %s",
           remote_host,
           *json_result ? "TRUE" : "false");

json_decref(val);

if (*json_result)
    applog(LOG_INFO, "PROOF-OF-WORK found");

/* if pool server mode, return success even if result==false */
if (srv.easy_target)
    *json_result = true;

out:
return rc;

我關心的是這部分:

/* if pool server mode, return success even if result==false */
if (srv.easy_target)
    *json_result = true;

在我的情況下 srv.easy_target 是真的。 那么 json_result 也將是 true,但是 if 語句放在 function 的末尾。 我只是不明白 json_result 將如何使用。 或者,即使在執行上述任何代碼之前,指針也會傳遞?

基本上放在 function 末尾的指針有什么用處?

json_result是一個指針,可能是來自外部的參數。 使用*取消引用它並更改它指向的值。

這是提供函數結果的一種非常標准的方式。 調用者傳遞一個指向其變量的指針,而被調用者完全按照這段代碼所做的事情:取消引用傳遞的指針並更改它指向的值,從而更改調用者的變量。

I can't be sure, since you didn't include the function signature in your code snippet, but if json_result is a pointer that is passed in as a function parameter, then it will be useful to the caller of the function. 在 C 中,當您希望能夠從 function 中返回多個值時,您通常會傳入指向將保存返回值的變量的指針。 這可能就是這里正在做的事情。

例如,標准庫 function scanf就是這樣做的。 您指定用於從標准輸入讀取值的格式字符串,然后為其提供指向變量的指針,該變量將用於存儲值。

int x;
char c;
float f;

scanf("%d %c %f", &x, &c, &f);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM