Thursday, 3 August 2017

c - type cast function arguments

I've been playing around with type casting in C. In particular, I've been (following K&R) trying to implement a program that will take "general" types of input (specifically, K&R implements a qsort that sorts an array of pointers to generic data). In doing so, I've encountered the following issue:



#include 

int comp(int *a, int *b); //*a == *b

main()
{
int a = 2;
int b = 3;

int *pa = &a;
int *pb = &b;

int (*pfunc)(void *, void *) = (int (*)(void *, void *)) comp;
int fin = (*pfunc)((void *)pa, (void *)pb);

printf("%d \n", fin);
}



This complies just fine, and does what you might expect it to do. The problem is that this:



#include 

main()
{
int a = 2;
int b = 3;
int *pa = &a;
int *pb = &b;


void *pVoid_a = (void *) pa;
void *pVoid_b = (void *) pb;

int fin_Void = (*pVoid_a == *pVoid_b);
}


doesn't work.




Why this is a problem: As I understand it, in the type cast



int (*pfunc)(void *, void *) = (int (*)(void *, void *)) comp;


a copy of the pointer "comp" is made, with the exception that the function this copy points to takes arguments "void *" rather than "int *", and is assigned to the variable "pfunc". Otherwise, pfunc and comp behave in the same way. (I think I must be wrong here, but I am unsure why)



When, in the first program, (void *)pa and (void *)pb are passed to pfunc, I would expect two copies of pa and pb to be made, with the exception that these are now of type (void *) and assigned to different names. These copies are sent through pcomp, the value returned is printed, etc.



I've attempted to recreate this process in the second program, except it DOESN'T work! For some reason, in the first program after pVoid_a and pVoid_b are passed to pfunc, they end up behaving like "int *"'s, in the body of the function, even though it doesn't seem like there's any reason for them to. Why do pVoid_a and pVoid_b recover their "int" behavior in the first program, but not in the second?

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...