Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminology when Initializing C Structures

This will be an easy question but googling around does not seem to provide me with an answer. The way I understand it in C we have two ways to initialize a foo object, when foo is a structure. 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 in C to these different initializing methods? The first returns an initialized pointer to foo so it's easy to use if you want a foo object on the heap like that:

foo* f1 = foo_init1(10,20,"hello");

But the second requires a foo .. what? Look at the code below.

foo f1;
foo_init2(&f1,10,20,"hello");

So the second method makes it easy to initialize an object on the stack but how do you call it? This is basically my question, how to refer to the second method of initialization.

The first one allocates and initializes a pointer to foo. The second one initializes a foo by ... what? Reference?

As a bonus question, how do you guys work when coding in C? Do you determine the usage of the object you are making and by that determine if you should have an initializing function of type1 , or 2 or even both of them?

like image 754
Lefteris Avatar asked Feb 23 '12 04:02

Lefteris


1 Answers

I am not sure if there are any well defined nomenclature for the two methods,
In the first method the function dynamically allocates a structure and assigns values to the members,
while in second the structure is allocated before the function and the function then just assigns values to the members.

Do you determine the usage of the object you are making and by that determine if you should have an initializing function of type1 , or 2 or even both of them?

Selecting first or second method depends on a important difference:
The first method is preferred when you need to pass the returned structure across scopes, the memory on heap has to be explicitly freed untill which the data prevails while in Second method the data on stack gets removed once the scope of the passed object ends.

like image 96
Alok Save Avatar answered Sep 21 '22 19:09

Alok Save