0% found this document useful (0 votes)
35 views7 pages

Struct

A structure is a user-defined data type that groups related data types under a single name. A union allows storing different data types in the same memory location, with only one data type stored at a time. The document provides examples of declaring and using structures and unions in C/C++ programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views7 pages

Struct

A structure is a user-defined data type that groups related data types under a single name. A union allows storing different data types in the same memory location, with only one data type stored at a time. The document provides examples of declaring and using structures and unions in C/C++ programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Structures

A structure is a user defined data type in C/C++. A structure creates a data type
that can be used to group items of possibly different types into a single type.
Keyword “struct” is used to create a structure.
struct address
{
// members or fields of structure
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

A structure variable can either be declared with structure declaration


struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'

or as a separate declaration like basic types.


struct Point
{
int x, y;
};

struct Point p1; // The variable p1 is declared like a normal variable

Note: In C++, the struct keyword is optional before in declaration of a variable. In


C, it is mandatory.

Structure members can be initialized using curly braces ‘{}’. Structure members
are accessed using dot (.) operator.
#include <stdio.h>

struct Point
{
int x, y;
};

int main()
{
struct Point p1 = { 4, 7 };
printf("x = %d, y = %d\n", p1.x, p1.y);

// Accesing members of point p1


p1.x = 20;
printf("x = %d, y = %d\n", p1.x, p1.y);
return 0;
}

Like other primitive data types, we can create an array of structures.


#include <stdio.h>

struct Point
{
int x, y;
};

int main()
{
// Create an array of structures
struct Point arr[5];

// Access array members


for (int i = 0; i < 5; i++)
{
arr[i].x = i * i;
arr[i].y = i + i;
}

for (int i = 0; i < 5; i++)


printf("%d %d\n", arr[i].x, arr[i].y);
return 0;
}

Like primitive types, we can have pointer to a structure. If we have a pointer to


structure, members are accessed using arrow ( –> ) operator.
(*p1).x is equivalent to p1–>x
#include <stdio.h>

struct Point
{
int x, y;
};

int main()
{
Point *p1 = new Point;
p1->x = 10; p1->y = 23;
printf("%d %d\n", p1->x, p1->y);

printf("%d %d\n", (*p1).x, (*p1).y);


delete p1;
return 0;
}

Size of the structure equals to the sum of sizes of its types.


#include <stdio.h>

struct Point
{
int x, y;
};

struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

int main()
{
printf("%d\n", sizeof(Point));
printf("%d\n", sizeof(address));
return 0;
}

This program explains how to use structure within structure in C using normal
variable. “student_college_detail” structure is declared inside “student_detail” structure
in this program. Both structure variables are normal structure variables.
#include <stdio.h>

struct student_college_detail
{
int college_id;
char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
} stu_data;

int main()
{
struct student_detail stu_data = { 1, "Raju", 90.5, 71145,
"Anna University" };
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);

printf(" College Id is: %d \n", stu_data.clg_data.college_id);


printf(" College Name is: %s \n", stu_data.clg_data.college_name);
return 0;
}

E-OLYMP 4817. Rectangle Find the perimeter and the area of a rectangle.
► Use struct rectangle to solve the problem.
#include <stdio.h>

struct rectangle
{
int x, y;
} a;

int GetPerimeter(struct rectangle p)


{
return 2 * (p.x + p.y);
}

int GetArea(struct rectangle p)


{
return p.x * p.y;
}

int main(void)
{
while (scanf("%d %d", &a.x, &a.y) == 2)
printf("%d %d\n", GetPerimeter(a), GetArea(a));
return 0;
}

E-OLYMP 972. Sorting time Sort the time according to specified criteria.
► Declare the time structure that contains hours, minutes and seconds.
struct MyTime
{
int hour, min, sec;
};

Declare the array of structures.


struct MyTime lst[100];

Function f returns 1 if a < b.


int f(MyTime a, MyTime b)
{

If hours and minutes are equal, sort the time in increasing order of seconds.
if ((a.hour == b.hour) && (a.min == b.min)) return a.sec < b.sec;

If hours are equal (minutes are not equal), sort the time in increasing order of
minutes.
if (a.hour == b.hour) return a.min < b.min;

Otherwise sort the time in increasing order of hours.


return a.hour < b.hour;
}
Function swap swaps the times a and b.
void swap(MyTime &a, MyTime &b)
{
MyTime temp = a; a = b; b = temp;
}

The main part of the problem. Read the input data.


scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d %d %d", &lst[i].hour, &lst[i].min, &lst[i].sec);

Sort the data using a swap sort.


for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (!f(lst[i], lst[j])) swap(lst[i], lst[j]);

Print the sorted data.


for (i = 0; i < n; i++)
printf("%d %d %d\n", lst[i].hour, lst[i].min, lst[i].sec);

Union
A union is a special data type available in C that allows to store different data
types in the same memory location. You can define a union with many members, but
only one member can contain a value at any given time. Unions provide an efficient
way of using the same memory location for multiple-purpose.

To define a union, you must use the union statement in the same way as you did
while defining a structure. The union statement defines a new data type with more than
one member for your program. The format of the union statement is as follows −
union[union tag]
{
member definition;
member definition;
...
member definition;
}[one or more union variables];

The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end of
the union’s definition, before the final semicolon, you can specify one or more union
variables but it is optional. Here is the way you would define a union type named Data
having three members:
#include <stdio.h>
union Data
{
int i;
float f;
char str[20];
};

int main()
{
union Data data;
printf("Memory size = %d\n", sizeof(data));
return 0;
}

Now, a variable of Data type can store an integer, a floating-point number, or a


string of characters. It means a single variable, i.e., same memory location, can be used
to store multiple types of data. You can use any built-in or user defined data types inside
a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member
of the union. For example, in the above example, Data type will occupy 20 bytes of
memory space because this is the maximum space which can be occupied by a character
string.

To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable name and the
union member that we wish to access.

#include <stdio.h>
#include <string.h>

union Data
{
int i;
float f;
char str[20];
};

int main()
{
union Data data;

data.i = 10;
data.f = 220.5;
strcpy(data.str, "C Programming");

printf("data.i : %d\n", data.i);


printf("data.f : %f\n", data.f);
printf("data.str : %s\n", data.str);

return 0;
}
When the above code is compiled and executed, it produces the following result

data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that the values of i and f members of union got corrupted because
the final value assigned to the variable has occupied the memory location and this is the
reason that the value of str member is getting printed very well.

Now let’s look into the same example once again where we will use one variable at
a time which is the main purpose of having unions −
#include <stdio.h>
#include <string.h>

union Data
{
int i;
float f;
char str[20];
};

int main()
{
union Data data;

data.i = 10;
printf("data.i : %d\n", data.i);

data.f = 220.5;
printf("data.f : %f\n", data.f);

strcpy(data.str, "C Programming");


printf("data.str : %s\n", data.str);

return 0;
}

When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being
used at a time.

You might also like