This will be a simple question, but a googling search doesn't seem to give me an answer. As I understand this in C, we have two ways to initialize the foo object when foo is a structure. Take a look at the code below for an example.
typedef struct foo { int var1; int var2; char* var3; }foo; //initializes and allocates a foo foo* foo_init1(int v1,int v2,const char* v3) { if(..some checks..) return 0; foo* ret = malloc(sizeof(foo)); ret->var1 = v1; ret->var2 = v2; ret-var3 = malloc(strlen(v3)+1); strcpy(ret->var3,v3); return ret; } // initializes foo by ... what? How do we call this method of initialization? char foo_init2(foo* ret,int v1,int v2, const char* v3) { //do some checks and return false if(...some checks..) return false//;assume you defined true and false in a header file as 1 and 0 respectively ret->var1 = v1; ret->var1 = v1; ret->var2 = v2; ret-var3 = malloc(strlen(v3)+1); strcpy(ret->var3,v3); return true; }
So my question is this. How do we refer to C for these various initialization methods? The first returns an initialized pointer to foo, so it's easy to use if you want the foo object on the heap to look like this:
foo* f1 = foo_init1(10,20,"hello");
But the second requires foo .. what? Take a look at the code below.
foo f1; foo_init2(&f1,10,20,"hello");
Thus, the second method simplifies the initialization of the object on the stack, but what do you call it? This is basically my question of how to access the second initialization method.
The first selects and initializes a pointer to foo. The second initializes foo ... what? Link
As a bonus question, how do you guys work when coding in C? Do you determine the use of the object you are creating and determine whether there should be an initialization function of type 1 or 2, or even both of them?
Lefteris
source share