Pelles C forum

C language => Expert questions => Topic started by: gedumer on November 07, 2008, 07:19:59 PM

Title: Shared pointers???
Post by: gedumer on November 07, 2008, 07:19:59 PM
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 "int i", so I wouldn't have to create 2 separate functions that do exactly the same thing? Let's assume I have a valid reason for having 2 separate structures. I would just like to share function "x" and eliminate function "y". I could have infinite structures that have "int i" and I'd like to use generic function "x" for all of them. Is there a way?

#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;
}
Title: Re: Shared pointers???
Post by: Stefan Pendl on November 08, 2008, 07:27:31 AM
The following might work:
// Function "x"
void x(void *p)
{
  (*p).i = 10;
}
// Function "y"
void y(void *p)
{
  (*p).i = 20;
}
Title: Re: Shared pointers???
Post by: gedumer on November 08, 2008, 04:44:08 PM
It appears to be an unsolvable problem, from a practical standpoint at least, so I've decided to go in another direction. Thanks.
Title: Re: Shared pointers???
Post by: pgoh on November 11, 2008, 08:23:34 AM
Quote from: Stefan Pendl on November 08, 2008, 07:27:31 AM
The following might work:
// Function "x"
void x(void *p)
{
  (*p).i = 10;
}
// Function "y"
void y(void *p)
{
  (*p).i = 20;
}


The code above will not work. That's because there is no type info contained within a void pointer. A better option would be to cast the point to an int pointer, and then set the value of the int pointer to whatever new value you wish.

Here's some code that does just 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;
}

void z(void *p) {
int *i = (int *)p;
*i = 55;
}

int main(void)
{
a a1;
b b1;
x(&a1);
y(&b1);
printf("a1.i = %d,  b1.i = %d\n", a1.i, b1.i);

z(&a1);
z(&b1);
printf("a1.i = %d,  b1.i = %d\n", a1.i, b1.i);

return 0;
}


A couple of caveats you need to be aware of when using this method:

Of course, what you're attempting to do sounds a lot like polymorphism. If that's the case, you might be better off using C++ instead of C.