Can somebody explain pointer typecasting in c.

Can somebody explain me pointer typecasting in c.
Who is Participating?
ssnkumarConnect With a Mentor Commented:
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.
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;

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);
   case 2:
     ptrStruct = (struct message2 *)someStruct;
     printf("%d %d %d %s\n", ptr2->x , ptr2->y ,ptr2->z, ptr2->message);

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:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.