我正在嘗試通過消息隊列發送整數。我將這個整數的地址強制轉換爲(char *),因爲將來我希望接受其他數據類型,並且此數據將發送到用於消息隊列的結構中。在c中的消息隊列中進行類型轉換
在消息隊列(我已經驗證到被正確地工作),我送一個結構類型:
struct Type{
long mtype;
char *data;
};
要發送信息,下面的代碼從發送處理中執行:
struct Type* ack = malloc(sizeof(struct Type));
int temp = 999;
ack->mtype = 1;
ack->data = (char *)&temp;
if(msgsnd(msqid, ack, sizeof(struct Type) - sizeof(long), 0) == -1){
perror("Sending acknowledgement to producer\n");
}
在接收器端,以下則執行:
struct Type *rack = malloc(sizeof(struct Type));
rack->mtype = 1;
//Wait for acknowledgement from server
if(msgrcv(prodmsqid, rack, sizeof(struct Type) - sizeof(long), 0, 0) == -1){
perror("msgrcv for acknowledgement from server");
exit(1);
}
printf("Acknowledgement has arrived: %d\n",(int)rack->data);
輸出這個printf從非常大的數字(8171536)變化到4.
不應該''(int *)rack-> data'?爲什麼不把結構的'data'成員改爲'int'而不是'char'指針呢? – Cyclonecode