[nzlug] C expert advise wanted
Eliot Blennerhassett
linux at blennerhassett.gen.nz
Thu Mar 29 16:09:11 NZST 2007
Raimund Eimann wrote:
> Hi,
>
> a C program I'm currently writing uses two very similar structs, say struct_a
> and struct_b.
>
> struct struct_a {
> var a;
> var b;
> struct struct_a *next;
> }
>
> struct struct_b {
> var a;
> var b;
> struct struct_a *c;
> struct struct_b *next;
> }
>
> In order to process these structs, I've got two functions proc_a() and
> proc_b(). Both function only operate on the (simple) variables a and b which
> exist in both struct and are of the same type.
It doesn't look like it. Each function mallocs a different struct...
> int proc_a(var *c, struct struct_a **a) {
> struct struct_a *dummy = malloc(...);
>
> dummy->a = ...
> dummy->b = ...
> ...
> *a = dummy;
> }
>
> int proc_b(var *c, struct struct_b **b) {
> struct struct_b *dummy = malloc(...);
>
> dummy->a = ...
> dummy->b = ...
> ...
> *b = dummy;
> }
>
> Is there some way of avoiding this code repetition and only have a single
> function which is capable of processing both types of structs?
Factor out the common parts...
struct common {
var a;
var b;
}
struct struct_a {
struct common c;
etc..
}
struct struct_b {
struct common c;
etc..
}
int proc_common ( struct common * c)
{
c->a = ....;
c->b = ... ;
}
int proc_a( )
{
struct struct_a dummy;
proc_common(&dummy->common);
}
int proc_b( )
{
struct struct_ dummy;
proc_common(&dummy->common);
}
> NZLUG mailing list NZLUG at linux.net.nz
> http://www.linux.net.nz/cgi-bin/mailman/listinfo/nzlug
More information about the NZLUG
mailing list