Struct Member Access - C Structure

C examples for Structure:Structure Definition

Introduction

Variables of a struct type are called fields or members.

These fields are accessed using the member of operator . prefixed by the object name.

Demo Code

typedef struct point point;

struct point {/*w  ww .j  av a 2 s  . com*/
  int x, y;
};

int main(void) {
  point p;
  p.x = 1;
  p.y = 2;
}

struct objects may also be initialized when they are declared by enclosing the values in curly brackets.

The values are assigned in order to the corresponding members of the struct.

Demo Code

typedef struct point point;

struct point {//w w w  .j  a v a 2  s .  c  om
  int x, y;
} r = { 1, 2 }; /* assigns x and y */

int main(void) {
  point p = { 1, 2 };
}

C99 standard introduced designated initializers.

It allow structures to be initialized in any order by specifying the names of the fields.

Any omitted fields will be automatically initialized to 0.

int main(void) {
  point p = { .y = 2, .x = 1 };
}

Related Tutorials