[英]Assign a void* variable to a struct variable
我有一個void *變量,正在通過套接字連接獲取。 我需要將其強制轉換為結構類型,這在客戶端和服務器端均已定義。
我在下面的代碼中提供了相關作業的示例。 在此示例中,為簡潔起見,我省略了網絡代碼。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int x;
int y;
} testStructType;
void someFunction(void* p)
{
//some processing goes here.
}
int main(void) {
testStructType testStruct;
void* p;
p=malloc(sizeof(testStructType));
someFunction(p);
testStruct=p;
printf("%i ,%i",testStruct.x,testStruct.y);
return EXIT_SUCCESS;
}
問題是當從'void *'分配給類型'testStructType'時,我得到了錯誤不兼容的類型
我究竟做錯了什么? 有人能幫幫我嗎?
你的意思是
testStruct = *(testStructType *)p;
為了獲得指針所指向的內容,您需要取消引用它。
這將復制該結構。 如果您實際上不需要副本,則可以直接訪問原始副本:
testStructType *pt = p;
printf("%i ,%i", pt->x, pt->y);
請注意,您不是在“通過套接字連接獲取void *變量”。 您正在通過套接字連接獲取一些數據,並且void *變量指向該數據。
這是一個指針,所以該行讀取
testStructType testStruct;
應該讀
testStructType *testStruct;
那么以下代碼需要更改為:
testStruct = (testStructType *)p;
printf("%d, %d", testStruct->x, testStruct->y);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.