G
gedumer1
Hi,
in C... is there any such thing as an "any" type pointer? In the example
below, is there any way that I could define function "x" to accept a pointer
of type "struct a" or "struct b", or any other structure I might create with
an "int i", so I wouldn't have to create multiple functions that do exactly
the same thing? Let's assume I have a valid reason for having separate
structures with similar data. I would just like to share function "x" and
eliminate function "y". I could have many more similar structures and I'd
like to use generic function "x" for all of them. Is there any way I can do
that?
#include <stdio.h>
// Structure "a"
typedef struct
{
int i;
} a;
// Structure "b"
typedef struct
{
int i;
char s[5];
} b;
// Function "x"
void x(a *p)
{
(*p).i = 10;
}
// Function "y"
void y(b *p)
{
(*p).i = 20;
}
int main(void)
{
a a1;
b b1;
x(&a1);
y(&b1);
printf("a1.i = %d, b1.i = %d\n", a1.i, b1.i);
return 0;
}
in C... is there any such thing as an "any" type pointer? In the example
below, is there any way that I could define function "x" to accept a pointer
of type "struct a" or "struct b", or any other structure I might create with
an "int i", so I wouldn't have to create multiple functions that do exactly
the same thing? Let's assume I have a valid reason for having separate
structures with similar data. I would just like to share function "x" and
eliminate function "y". I could have many more similar structures and I'd
like to use generic function "x" for all of them. Is there any way I can do
that?
#include <stdio.h>
// Structure "a"
typedef struct
{
int i;
} a;
// Structure "b"
typedef struct
{
int i;
char s[5];
} b;
// Function "x"
void x(a *p)
{
(*p).i = 10;
}
// Function "y"
void y(b *p)
{
(*p).i = 20;
}
int main(void)
{
a a1;
b b1;
x(&a1);
y(&b1);
printf("a1.i = %d, b1.i = %d\n", a1.i, b1.i);
return 0;
}