Revision : Structure

Question :

What are the differences between all the lines below?

typedef struct st { int st; } st;

typedef struct { int st; } st;

typedef struct st st;

struct st { int st; } st;

struct st { int st; };

struct st st;

st st;

Confused? Okay, let’s figure it out one by one.

Using keyword struct

Let’s start with :

struct stTag { int i; float f; };

This line means we want to declare a structure which has data value named i and f. The structure has a tag name that is called stTag. To use this structure tag to declare structure variables, we declare them this way :

struct stTag stVar1,stVar2;

The keyword struct must always appear before the structure tag whenever the tag is used in the program as well as in the function parameters declaration.

We can always combine the structure declaration with the variable declaration this way :

struct stTag { int i; float f; } stVar1, stVar2;

Once the tag has been defined, it can be used to declare other variables just as before :

struct stTag stVar3, stVar4;

Using keyword typedef

Alternatively, to avoid having to always use the keyword struct, you can always use the keyword typedef to define a user-defined data type. This is how to do it :

typedef struct stTag { int i; float f; } stType;

After that, you can use either the user-defined type name or the structure tag to declare other variables, examples are :

struct stTag stVar5, stVar6;

stType stVar7, stVar8;

When using typedef to define a struct, the structure tag is optional and can be omitted, for example :

typedef struct { int i; float f; } stType;

We can also define a user-defined type using typedef based on a defined structure tag, for example :

struct stTag { int i; float f; };

typedef struct stTag stType;

struct in C++

In C++, the structure tag is a type name and we do not need to use the keyword struct to identify a variable as a structure, this mean that the following is valid in C++ but not in C language :

struct stTag { int i; float f; };

stTag stVar1,stVar2;

Accessing structure

To access the data members of a structure, the member access operator (that is the dot operator ‘.’) is used. To access the data members of a structure pointed by a pointer, we can use the indirect member access operator (the arrow operator ‘->’).

Example :

struct Point { float x,y; };

....

Point p1; Point q[10];

p1.x = 1.2; p1.y = 3.2;

cout < p1.x < p1.y;

....

i = 4;

q[i].x = 5.4; q[i].y = 7.6;

cout < q[i].x < q[i].y;

....

Point *ptr;

ptr = &p1;

ptr->x = 2.3; ptr->y = 9.8;

cout < ptr->x < ptr->y;

....

Take note that ptr->x is the same as (*ptr).x;