A detailed explanation of structural variable privatization in C

  • 2020-06-07 04:58:54
  • OfStack

background

Operating system: CentOS7.3.1611_x64

gcc version: 4.8.5

What is a structure?

In C, a structure (struct) refers to a data structure and is a class of aggregated data types (aggregate data type) in C. Structures can be declared as variables, Pointers, arrays, and so on to implement more complex data structures. The struct is also a collection of 1 elements, called members of the struct (member), which can be of different types. Members 1 are generally accessed by name.

Problem description

By default, variables in the C language structure definition are public (Public). What if member variables are private (Private)?

The solution

The definition of the structure is implemented in the source code, and the header file is only the declaration.

For example, you have the following structure (defined in the obj.h file) :


struct Obj {
 int id;
 char *name;
};
typedef struct Obj Obj;

And define the following variables:


Obj *o;

Variables in the structure can normally be accessed using the following code:


printf("id : %d\n",o->id);

If you put the definition of the structure in the source file, the code will report the following error:


error: dereferencing pointer to incomplete type
 printf("id : %d\n",o->id);

If external access is required, this can be achieved by adding relevant interfaces, such as:


int get_obj_id(const Obj* o)
{
 int ret = 0;
 if(o)
 {
  ret = o.id;
 }
 return ret;
}

The complete sample code is as follows:

https://github.com/mike-zhang/cppExamples/tree/master/dataTypeOpt/CStructPrivateTest1

Well, that's all. I hope it helped.

conclusion


Related articles: