Re: void* passed as funtion parameters?
Hello Igor,
Why? Are you being charged per line of code?
The code in the function below really doesn't mean much but its just to
illustrate that keeping the cast(s) doesn't get rid of the redundance in the
f1() function. I showed an example below where suppose I have more code
residing in f1(), keeping the casts don't solve the problem. I understand the
part about the casts, but am I supposed to end up with something like this
for all my functions?
============================
typedef struct tag_pc {
long LK__F1;
long LK__F2;
long h;
} pc;
typedef struct tag_ab {
long LK__F1;
long LK__F2;
long h;
} ab;
typedef struct tag_cd {
long LK__F1;
long LK__F2;
long h;
} cd;
void f1(void *x, int type, int z)
{
int y;
pc *p = x;
ab *q =x;
cd *r =x;
switch(type)
{
case 1:
for(y=0; y<100; y++)
{
if(y==z)
{
p->LK__F1 = y;
p->LK__F2 = (y+12);
}
p->h = y+z;
}
break;
case 2:
for(y=0; y<100; y++)
{
if(y==z)
{
q->LK__F1 = y;
q->LK__F2 = (y+12);
}
q->h = y+z;
}
break;
case 2:
for(y=0; y<100; y++)
{
if(y==z)
{
r->LK__F1 = y;
r->LK__F2 = (y+12);
}
r->h = y+z;
}
break;
}
}
int main()
{
void *x;
x = malloc (sizeof (struct tag_pc));
f1(x, 1);
x = malloc (sizeof (struct tag_ab));
f1(x, 2);
x = malloc (sizeof (struct tag_cd));
f1(x, 3);
free(x);
return 0;
}
===========================
I find f1() very redundant, and bulky, wouldn't you agree?
Igor, I am looking for an alternative, and gentlemen in this post have
listed the alternatives whereby the way I see it, asides from what was
proposed, theres not much more I can do becuase its C.
Thanks all for your help!
--
Best regards
Roberto
"Igor Tandetnik" wrote:
Robby wrote:
void f1(void *x)
{
pc *p = x;
p->LK__F1 = 10;
}
*but then* How do I know what pointer *type* is comming in the
function ???
Since all the structures are layout-compatible, it doesn't really
matter. LK__F1 is the same size and at the same offset in all three
structures, so the assignment would work the same regardless of
which of the three types you cast to. Your code should work as
written.
Yes, but I wanted to get away with writting the above function
without using this line:
pc *p = x;
Why? Are you being charged per line of code?
But in C we can't. Unless I don't understand what you mean.
"Your code should work as written" sounds pretty unambiguous to me.
Why is everyone talking about a cast. Is there a cast in this line? :
//pc *p = x;
Well, not a cast, but there's a conversion (once you remove two slashes
in front so that it's not just a comment). In C++, such a conversion
would in fact require an explicit cast, but in C it happens implicitly.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925