0
votes

I have a void* variable which I am getting through a socket connection. 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*'

What am I doing wrong? Can somebody please help me?

2
The assignment testStruct=p will fail, because testStruct is a structure, and p is a generic pointer. Actually, you probably don't need to use generic pointers (i.e. void *) at all. Just use pointers to the structure, and try to use that as much as you can. Many socket receive/send functions wants char * for data, but then just cast the pointer to the structure when needed. If a function expects a generic pointer, then no casting is needed at all. - Some programmer dude
testStruct=p; : Different type as (testStructType) = (void*), change to testStruct=*(testStructType *)p; - BLUEPIXY
And, of course, the program at both ends of the socket should be compiled using the same version of the same compiler, invoked with the same flags, and running on the same OS. It only takes a little change to make the structs at each end incompatible. - Nisse Engström

2 Answers

1
votes

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". You are getting some data through a socket connection, and the void* variable is pointing at that data.

0
votes

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);