Link to home
Start Free TrialLog in
Avatar of tpat
tpat

asked on

Can somebody explain pointer typecasting in c.

Can somebody explain me pointer typecasting in c.
Avatar of wesly_chen
wesly_chen
Flag of United States of America image

Avatar of phoffric
phoffric

Suppose you have a function that can process several different structs:
    void processSeveralDifferentStucts( void * someStruct, int messageType );

Your code might look like:
struct message1 { // ~ messageType = 1
int a;
int b;
short c;
}msg1;

struct message2{ // ~ messageType = 2
int x;
short y;
short z;
char message[20];
} msg2;

processSeveralDifferentStucts( &msg1, 1);
processSeveralDifferentStucts( &msg2, 2);

Open in new window

No typecasting is required here (but it is desirable, for clarities sake) because C allows conversion of pointers to void* without typecasting. However, typecasting is required in processSeveralDifferentStucts.
void processSeveralDifferentStucts( void * someStruct, int messageType ) {
  struct message1 ptr1; 
  struct message2 ptr2;
  switch (messageType) {
   case 1:
     ptr1 = (struct message1 *)someStruct;
     printf("%d %d %d \n", ptr1->a , ptr1->b ,ptr1->c);
     break;
   case 2:
     ptrStruct = (struct message2 *)someStruct;
     printf("%d %d %d %s\n", ptr2->x , ptr2->y ,ptr2->z, ptr2->message);
     break;
  }
}

Open in new window

Well, typecasting here isn't required because, again, C allows a void* pointer to be assigned to another pointer of a different type without the cast.

But suppose you were doing a TCP accept:
   int accept(int socket, struct sockaddr *address, socklen_t *restrict address_len);

Now, when using accept, you have to typecast the 2nd argument in the call because you will not get automatic conversion to the type of the passed in pointer.
    struct sockaddr_in serv_addr, cli_addr;
    newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

Open in new window

The above two lines were take from:
    http://www.linuxhowtos.org/C_C++/socket.htm
ASKER CERTIFIED SOLUTION
Avatar of Narendra Kumar S S
Narendra Kumar S S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial