Reputation: 2852
I am trying to build a constructor-like function for structs in C. I'm best with languages built around object-oriented features, and adding object-oriented features to a bare-bones language is not my forte. Unfortunately, for this project, however, I am forced to use a variation of C.
The idea is to build a function with a parameter for each variable in the struct that needs to be initialized, along with a 'name' parameter for the name of the struct.
The biggest issue is that the variation of C I need to use is very limited in features. It doesn't seem to have dynamic memory allocation, among other things.
The goal code would be something like this:
typedef struct {
int a;
string b;
} TheStruct;
void newStruct(string name, int a, string b){
TheStruct name;
name.a = a;
name.b = b;
}
This won't work, because the struct instantiated with be called 'name' rather than the value of the name variable. How, without using higher-level features not found in C like variable variables, could a struct be dynamically referenced this way in C?
Upvotes: 1
Views: 296
Reputation: 29794
Two choices:
struct TheStruct
by reference to the newStruct
methodstruct TheStruct
from newStruct
) which later you'll have to delete using free
The method could be something like this:
typedef struct {
int a;
string b;
} TheStruct;
void newStruct(TheStruct* st, string name, int a, string b){
st->a = a;
st->b = b;
}
or
TheStruct* newStruct(string name, int a, string b){
TheStruct *res = malloc(sizeof(TheStruct));
res->a = a;
res->b = b;
return res;
}
You can take a look at this tutorial which is very nice: Pointers in C++. Is for C++ but the basics are pretty much the same.
Upvotes: 2
Reputation: 9648
You want to pass a TheStruct
in by reference or return a pointer to a new struct.
void newStruct( TheStruct* s, int a, string b )
{
if( !s )
s = malloc( sizeof( TheStruct ) );
s->a = a;
s->b = b;
}
//or
TheStruct* newStruct( int a, string b )
{
TheStruct* s = malloc( sizeof( TheStruct ) );
s->a = a;
s->b = b;
return s;
}
NOTE: when using the second version, you will have to remember to clean up the memory since it is created on the heap. With the first version, TheStruct
could be created on the stack or the heap. (I assume a and b are defined.)
TheStruct s1, *s2;
s2 = malloc( sizeof( TheStruct ) );
newStruct( &s1, a, b );
newStruct( s2, a, b );
// do stuff
free( s2 );
In the second version it would look like:
TheStruct *s3 = newStruct( a, b );
// do stuff
free( s3 );
Upvotes: 0