Problem with pointer and structure

1

Having the following code:

DWORD WINAPI redirect(LPVOID param)
{
SOCKET rsock, csock;
SOCKADDR_IN rssin, cssin;
rs rs2;
DWORD id;

rs2 = *((rs *)param);
rsock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
WSAAsyncSelect(rsock, 0, WM_USER + 1, FD_READ);
memset(&rssin, 0, sizeof(rssin));
rssin.sin_family = AF_INET;
rssin.sin_port = htons(rs2.lport);
bind(rsock, (SOCKADDR *)&rssin, sizeof(rssin));

while(1) {
    if (listen(rsock, 10) == SOCKET_ERROR) break;
    csock = accept(rsock, (SOCKADDR *)&cssin, NULL);
    if (csock != INVALID_SOCKET) {
        rs2.csock = csock;
        CreateThread(NULL, 0, &redirectloop, (void *)&rs2, 0, &id);
    }
}

closesocket(csock);
closesocket(rsock);

return 0;
}

I do not understand very well what this pointer is doing in this structure rs2 = *((rs *)param);

    
asked by thc 21.06.2018 в 00:02
source

1 answer

2

For ease of explanation, this equivalent code:

DWORD WINAPI redirect(LPVOID param)
{
   rs rs2, *pRs;

   pRs = (rs *)param;
   rs2 = *pRs;

param is LPVOID, which is a pointer without a defined type ( void * , if it sounds like something).

rs2 is a variable of type rs , which I assume will be a struct .

(rs *) param is a cast, tells the compiler that param is a rs * , a pointer that points to a structure of type rs

*pRs makes a dereferencing, it means that the value of the structure rs pointed.

rs2 = *pRs copies the values of the dereferenced structure in rs2 .

It looks easier with concrete values, in this case int .

int *pInt = (int *)malloc(sizeof(int)); // 'pInt' apunta a una dirección X
*pInt = 6;                              // Metemos 6 en la dirección X
LPVOID param = (LPVOID) pInt           // param es X
int valor, *pValor;
pValor = (int *)param;                  // cast, pValor es X
valor = *pValor;                        // dereferencia, valor es 6 (el contenido de la dirección X).
    
answered by 01.07.2018 / 01:22
source