tpat
asked on
Can somebody explain pointer typecasting in c.
Can somebody explain me pointer typecasting in c.
Suppose you have a function that can process several different structs:
void processSeveralDifferentStu cts( void * someStruct, int messageType );
Your code might look like: cts.
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.
http://www.linuxhowtos.org/C_C++/socket.htm
void processSeveralDifferentStu
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);
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 processSeveralDifferentStuvoid 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;
}
}
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);
The above two lines were take from:http://www.linuxhowtos.org/C_C++/socket.htm
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
http://www.blurtit.com/q310389.html
example with explanation
http://bytes.com/topic/c/answers/594439-typecasting-pointers
http://bytes.com/topic/c/answers/622284-pointer-type-casting