简体   繁体   English

将void *变量分配给struct变量

[英]Assign a void* variable to a struct variable

I have a void* variable which I am getting through a socket connection. 我有一个void *变量,正在通过套接字连接获取。 I need to cast this to a struct type, wich is defined both on the client and server side. 我需要将其强制转换为结构类型,这在客户端和服务器端均已定义。

I have provided a sample of the assignment in question in the code below. 我在下面的代码中提供了相关作业的示例。 In the example I am leaving out the networking code for the sake of briefness. 在此示例中,为简洁起见,我省略了网络代码。

#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;
}

The problem is that I get error incompatible types when assigning to type 'testStructType' from 'void*' 问题是当从'void *'分配给类型'testStructType'时,我得到了错误不兼容的类型

What am I doing wrong? 我究竟做错了什么? Can somebody please help me? 有人能帮帮我吗?

You mean 你的意思是

testStruct = *(testStructType *)p;

To get at the contents of what a pointer points at, you need to dereference it. 为了获得指针所指向的内容,您需要取消引用它。

This makes a copy of the struct. 这将复制该结构。 If you don't actually need a copy then you can access the original directly: 如果您实际上不需要副本,则可以直接访问原始副本:

testStructType *pt = p;
printf("%i ,%i", pt->x, pt->y);

Note that you are not "getting a void* variable through a socket connection". 请注意,您不是在“通过套接字连接获取void *变量”。 You are getting some data through a socket connection, and the void* variable is pointing at that data. 您正在通过套接字连接获取一些数据,并且void *变量指向该数据。

It's a pointer, so the line that reads 这是一个指针,所以该行读取

    testStructType testStruct;

should read 应该读

    testStructType *testStruct;

then the following code needs to change to: 那么以下代码需要更改为:

    testStruct = (testStructType *)p;

    printf("%d, %d", testStruct->x, testStruct->y);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM