• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 576
  • Last Modified:

Can somebody explain pointer typecasting in c.

Can somebody explain me pointer typecasting in c.
0
tpat
Asked:
tpat
  • 2
1 Solution
 
phoffricCommented:
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
0
 
ssnkumarCommented:
Since you are already doing socket programming,
the accept call explained by "phoffric" is a good example.
The same kind of pointer typecasting is needed in bind.

Mainly, typecasting is needed, wherever the type in the caller and the type in the prototype don't match.
Since, all pointers takeup only 4 bytes of space, you can typecast any pointer type to any other pointer type.
But, inside the called function, you will have to take care to unfold it in proper way.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now