簡體   English   中英

c 代碼中的“(void *)2”是什么意思?

[英]what's the meaning of "(void *)2" in c code?

我最近讀了一本關於如何在 unix 環境中編寫代碼的書。有一個示例代碼讓我很困惑。

示例代碼:

#include "apue.h"
#include <pthread.h>

void *
thr_fn1(void *arg) {
  printf("thread 1 returning\n");
  return ((void *)1);
}

void *
thr_fn2(void *arg) {
  printf("thread 2 exiting\n");
  pthread_exit((void *)2);
}

int 
main(void) {
  int err;
  pthread_t tid1, tid2;
  void *tret;

  err = pthread_create(&tid1, NULL, thr_fn1, NULL);
  if (err != 0) {
    err_exit(err, "can't create thread 1");
  }
  err = pthread_create(&tid2, NULL, thr_fn2, NULL);
  if (err != 0) {
    err_exit(err, "can't create thread 2");
  }
  err = pthread_join(tid1, &tret);
  if (err != 0) {
    err_exit(err, "can't join with thread 1");
  }
  printf("thread 1 exit code %ld\n", (long)tret);
  err = pthread_join(tid2, &tret);
  if (err != 0) {
    err_exit(err, "can't join with thread 2");
  }
  printf("thread 2 exit code %ld\n", (long)tret);
  exit(0);
}

如何找出“(void *)1”或“(void *)2”? 可以將類型“void *”轉換為“long”嗎? 在我看來,“(void *)1”告訴我 1 是一個地址,但是當我使用 deref 來獲取存儲在地址 1 的值時,這顯然是錯誤的。 所以,我認為這段代碼很瘋狂。

c 代碼中的“(void *)2”是什么意思?

這意味着將值 2 轉換為“指向void的指針”類型。

pthread_exit((void *)2);

通常一個線程應該返回一個指向數據的指針(或者使用正常的 function 返回機制或者通過它作為參數傳遞給pthread_exit )。 在這種情況下,數據太小了,作者認為不值得為數據分配 memory; 他們將簡單地使用指針本身來表示數據。 所以他們將所需的值轉換為void *類型。

C 標准並未完全定義此行為,但它適用於許多 C 實現,尤其是 Unix 系統的實現。 調用者應將void *轉換回 integer 類型以解釋該值。

暫無
暫無

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

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