Vous êtes sur la page 1sur 18

UNIT 6 Structure and Union in C

By- Vivek Kumar

Structure Assignment
You can use structures just like variables:
StudentRecord s1,s2; s1.name = "Joe Student"; Copies the entire structure s2 = s1;

Accessing Struct Members


Individual members of a struct variable may be accessed using the structure member operator (the dot, .): mystruct.letter ; by using the structure pointer operator (the ->): myptr -> letter ; which could also be written as: (*myptr).letter ;

Nested Structure/Structure within Structure


Definition: A structure that contains the another structure(s) as a member is known as nested structure. struct student { int roll; char name[20]; struct { int day; int month; int year; } birthday; } s; s.birthday.day s.birthday.month s.birthday.year

Array of Structure
struct student { int roll; char name[20]; int age; Char class[8]; } s[50]; Example: S[1].roll=100; S[5].roll=1005; S[1].age=30;

Union: A union is like a struct, but only one of its members is stored, not all Union sample { int x; float y; Char z; }; union sample code;

1200

1201

1202

1203

All the members of the structure can be accessed at once,where as in an union only one member can be used at a time. Another important difference is in the size allocated to a structure and an union. For eg: struct example { int integer; float floating_numbers; } the size allocated here is sizeof(int)+sizeof(float); where as in an union union example { int integer; float floating_numbers; } size allocated is the size of the highest member. so size is=sizeof(float); All the members of the structure can be accessed at once,where as in an union only one member can be used at a time.

Difference b/w Structure and union

The sizeof Operator


The sizeof operator gives the amount of storage, in bytes, required to store an object of the type of the operand. This operator allows you to avoid specifying machine-dependent data sizes in your programs.
sizeof unary-expression

sizeof ( type-name )

The operand can also be a data type, in which case the result is the length in bytes of objects of that type:
sizeof(char) /* 1

sizeof(float) /* 4
sizeof(int ) /* 2

Example
You can use the sizeof operator to obtain information about the sizes of objects in your C environment. The following prints the sizes of the basic data types: /* Program name is "sizeof_example". This program * demonstrates a few uses of the sizeof operator. */ #include <stdio.h> int main(void) { printf("TYPE\t\tSIZE\n\n"); printf("char\t\t%d\n", sizeof(char)); printf("short\t\t%d\n", sizeof(short)); printf("int\t\t%d\n", sizeof(int)); printf("float\t\t%d\n", sizeof(float)); printf("double\t\t%d\n", sizeof(double)); }

If you execute this program, you get the following output:


TYPE char short int float double SIZE 1 2 4 4 8

Vous aimerez peut-être aussi