0% found this document useful (0 votes)
27 views16 pages

Unit-4 Intro To Prog (AK23)

This document covers pointers and user-defined data types in programming, specifically focusing on pointers, dereferencing, address operators, and pointer arithmetic. It also introduces structures and unions, explaining their definitions, features, and how to declare and initialize them. Examples are provided to illustrate the concepts of pointers and structures in C programming.

Uploaded by

padhu6121985
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)
27 views16 pages

Unit-4 Intro To Prog (AK23)

This document covers pointers and user-defined data types in programming, specifically focusing on pointers, dereferencing, address operators, and pointer arithmetic. It also introduces structures and unions, explaining their definitions, features, and how to declare and initialize them. Examples are provided to illustrate the concepts of pointers and structures in C programming.

Uploaded by

padhu6121985
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/ 16

UNIT 4

Pointers & User Defined Data types


Pointers, dereferencing and address operators, pointer and address arithmetic, array
manipulation using pointers, User-defined data types-Structures and Unions.

POINTERS: .

Introduction to Pointers:

In programming, a pointer is a variable that stores the memory address of another variable. Pointers
are used to work with memory directly and enable dynamic memory allocation and manipulation. To declare
a pointer, use the data type followed by an asterisk (*) and the name of the pointer variable.

You can initialize a pointer with the address of another variable. To access the value stored at the
memory address pointed to by a pointer, you use the dereference operator (*).

Pointers are commonly used for dynamic memory allocation, passing parameters to functions by
reference, and working with arrays and structures. Pointers are powerful but avoid issues like dereferencing
null pointers or accessing memory out of bounds.

Definition:

Pointer is defined as a derived data type that can store the address of another variable or a memory
location. (or)

Pointer is a variable which stores the address of another variable. This variable can be of type int, char,
array, function, or any other pointer. (or)

Pointer is a variable that stores the memory address of another variable as its value. A pointer variable
points to a data type (like int) of the same type, and is created with the * operator.

Example:
int n = 10;
int *p = &n; // variable p of type pointer is pointing to the address of the variable n of integer data type

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 1
Features of pointers:
Pointers are used frequently in c, as they offer a number of benefits to the programmers.

1. Pointers save the memory space.


2. Execution time with pointer is faster because data is manipulated with the address i.e., direct access
to memory address.
3. Pointers reduce length and complexity of programs.
4. A pointer allows C to support dynamic memory management.
5. Pointers are useful for representing two-dimensional and multi-dimensional arrays.
6. Pointers are used with data structures.

Dereferencing and address operators: .


The Dereference / Indirection operator:

Pointer is a variable that stores the address of another variable. The dereference operator is also known
as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer
variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the
variable pointed by this pointer will be returned.

Dereferencing is used to access or find out the data which is contained in the memory location which
is pointed by the pointer. The * (asterisk) operator which is also known as the C dereference pointer is used
with the pointer variable to dereference the pointer.

Example: int *ptr;

Address operator:

The Address Operator in C is a special unary operator that returns the address of a variable. It is denoted
as the Ampersand Symbol ( & ). This operator returns an integer value which is the address of its operand in
the memory.

Example: int num = 10;


printf("The address of num is %p", &num); // output: The address of num is 0x7fff5fbff7ac

Note: The memory address is printed using the “%p” format specifier in hexadecimal format.

Example 1: Program to explain the dereference & the address operators.

#include <stdio.h>
int main()
{
int x = 9; // declare the integer variable x
int *ptr; // declare the integer pointer variable ptr
ptr = &x; // store the address of 'x' variable to the pointer variable 'ptr'
*ptr = 14; // change the value of 'x' variable by dereferencing a pointer 'ptr'
printf("value of x is: %d", x); // value of 'x' from 9 to 14 because 'ptr' points to 'x' location and
return 0; //dereferencing of 'ptr'
}

Output: value of x is: 14


Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 2
Example 2: Program to explain the dereference & the address operators.

#include<stdio.h>
int main()
{
int u = 3;
int v;
int *pu;
int *pv;

pu = &u;
v = *pu;
pv = &v;

printf("\n u=%d &u=%u pu=%u *pu=%d", u, &u, pu, *pu);


printf("\n\n v=%d &v=%X pv=%X *pv=%d ", v, &v, pv, *pv);

return(0);
}

Output:
u=3 &u=6684356 pu=6684356 *pu=3

v=3 &v=65FEC0 pv=65FEC0 *pv=3

Note:
pu is a pointer to u, and pv is a pointer to v. therefore pu represent the address of u, and pv represents
the address of v. The output shown above is, in the first printf we have printed the address of variables output
with unsigned integer (%u) , and in the Second printf the address of variables is printed with hexa decimal
values (%X).

Example 3: Program to explain the different Arithmetic operation using pointers.

#include<stdio.h>
int main()
{
int a = 25, b = 10, *p, *j;
p = &a;
j = &b;
printf("Addition a + b = %d \n", *p + b);
printf("Subtraction a – b = %d \n", *p - b);
printf("Multiplication a * b = %d \n", *p * *j);
printf("Division a / b = %d \n", *p / *j);
printf(" Modulo division a % b = %d \n", *p % *j);
return(0);
}

Output:
Addition a + b = 35
Subtraction a - b = 15
Multiplication a * b = 250
Division a /b = 2
Modulo division a % b = 5

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 3
Pointer and Address arithmetic: .

Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The
pointer variables store the memory address of another variable. It doesn’t store any value.

Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C
pointer arithmetic operations are slightly different from the ones that we generally use for mathematical
calculations.

These operations are:


1. Increment / Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers

Example:

Data type Initial address Operation Address after operations Required bytes
int i = 2 4046 ++ -- 4048 4044 2 bytes
char c = ’x’ 4053 ++ -- 4054 4052 1 bytes
float f = 4.2 4058 ++ -- 4062 4054 4 bytes
long int l = 2 4060 ++ -- 4064 4056 4 bytes

From the above table we can observe that on increase of pointer variable for integers the address is
increased by two 4046 is original address and on increase its value will be 4048 because integer requires two
bytes.
Similarly characters, float numbers and long integers requires 1, 4 and 4 bytes respectively.

1.1 Increment of a Pointer 1.2 Decrement of a Pointer

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int n; int n;
int *ptr; // pointer to an integer int *ptr; // pointer to an integer
ptr = &n; ptr = &n;

printf("sizeof(int) is: %d bytes", sizeof(int)); printf("sizeof(int) is: %d bytes", sizeof(int));

printf("Pointer ptr before Increment: %d \n", ptr); printf("Pointer ptr before Increment: %d \n", ptr);
ptr++; // Increment of ptr++ ptr--; // Decrement of ptr--
printf("Pointer ptr after Increment: %d \n", ptr); printf("Pointer ptr after Increment: %d \n", ptr);

return 0; return 0;
} }

Output: sizeof(int) is: 2 bytes Output: sizeof(int) is: 2 bytes


Pointer ptr before Increment: 6684360 Pointer ptr before Increment: 6684360
Pointer ptr after Increment : 6684362 Pointer ptr after Increment : 6684358

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 4
2. Addition of integer to a pointer 3. Subtraction of integer to a pointer

#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int n; int n;
int *ptr; // pointer to an integer int *ptr; // pointer to an integer
ptr = &n; ptr = &n;

printf("sizeof(int) is: %d bytes", sizeof(int)); printf("sizeof(int) is: %d bytes", sizeof(int));

printf("Pointer ptr before Addition: %d \n", ptr); printf("Pointer ptr before Subtraction: %d \n", ptr);
ptr = ptr + 3; // addition of 3 to ptr ptr = ptr - 3; // Subtraction of 3 to ptr
printf("Pointer ptr after Addition: %d \n", ptr); printf("Pointer ptr after Subtraction: %d \n", ptr);

return 0; return 0;
} }

Output: sizeof(int) is: 2 bytes Output: sizeof(int) is: 2 bytes


Pointer ptr before Addition: 6684360 Pointer ptr before Subtraction: 6684360
Pointer ptr after Addition : 6684366 Pointer ptr after Subtraction : 6684354

4. Subtracting two pointers of the same type 5. Comparison of pointers

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


int main() int main()
{ {
int m, n, tot; int arr[5]; // declaring an array
int *ptr1, *ptr2; // pointers to an integer int *ptr1, *ptr2; // pointers to an integer array
ptr1 = &m; ptr1 = &arr; // declaring pointer to array name
ptr2 = &n; ptr2 = &arr[0]; // declaring pointer to first element

printf("sizeof(int) is: %d bytes", sizeof(int)); if (ptr1 == ptr2)


{ printf("Pointer to arr & 1st element are Equal."); }
printf(" ptr1 = %d, ptr2 = %d\n", ptr1, ptr2); else
tot = ptr1 - ptr2; // Subtraction of ptr2 and ptr1 { printf("Pointer to arr & 1st element are not Equal."); }
printf("Subtraction of ptr1 & ptr2 is: %d\n", tot);
return 0;
return 0; }
}
Output:
Output: sizeof(int) is: 2 bytes
ptr1 = 6684352, ptr2 = 6684350 Pointer to Array Name and First Element are Equal.
Subtraction of ptr1 & ptr2 is: 1

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 5
Array manipulation using pointers: .
Pointer array is a homogeneous collection of indexed pointer variables that are references to a memory
location. It is generally used in C Programming when we want to point at multiple memory locations of a
similar data type in our C program. We can access the data by dereferencing the pointer pointing to it.

Syntax:
pointer_type *array_name [array_size];

Here, pointer_type: Type of data the pointer is pointing to.


array_name : Name of the array of pointers.
array_size : Size of the array of pointers.

Note: It is important to keep in mind the operator precedence and associativity in the array of pointers
declarations of different type as a single change will mean the whole different thing.

For example, enclosing *array_name in the parenthesis will mean that array_name is a pointer to an array.

Example: C program to demonstrate the use of array of pointers

#include <stdio.h>
int main()
{

int var1 = 10; // declaring some temp variables


int var2 = 20;
int var3 = 30;

int *ptr_arr[3] = { &var1, &var2, &var3 }; // array of pointers to integers

for (int i = 0; i < 3; i++) // traversing using loop


{
printf("Value of var%d: %d\tAddress: %d \n", i + 1, *ptr_arr[i], ptr_arr[i]);
}

return 0;
}

Output:
Value of var1: 10 Address: 6684360
Value of var2: 20 Address: 6684356
Value of var3: 30 Address: 6684352

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 6
USER-DEFINED DATA TYPES - Structures and Unions:
STRUCTURES [ BASICS OF STRUCTURES ]
Definition of Structure:
A Structure is a collection of one or more variables of different data types, grouped together under a
single name. (or)

A Structure is a collection of data items of different data types under a single name.
Features of Structures:
• Structures are used to hold related data belonging to different data types.
• Nesting of Structures is possible.
• It is also possible to pass Structure elements to a function.
• It is also possible to create Structure pointers.

Declaration of Structure:
Structure can be declared as given below,
Syntax:
struct <structure-name>
{
data_type member-1;
data_type member-2;
--- --- ---
data_type member-n;
};
struct <structure-name> variable-1, variable-2, … … , variable-n;
• Structure declaration always starts with struct keyword. Here, structure-name is known as tag.
• The struct declaration is enclosed with in a, pair of curly braces.
• Each member of structure may belong to different types of data.
• The individual members can be ordinary variables, arrays, pointers or other structures.

E.g. :
struct account struct account
{ {
int ac_no; int ac_no;
char ac_type; char ac_type;
(or)
char name[25]; char name[25];
float balance; float balance;
}; } oldcustomer, newcustomer;
struct account oldcustomer, newcustomer;

Here structure name is account. It contains four members.


• Members of structure themselves do not occupy any space. Memory is allocated only after declaring
structure variables.

Example for structures:


Student : regno, student_name, age, address
Book : bookid, bookname, author, price, edition, publisher, year
Employee : employeeid, employee_name, age, sex, dateofbirth, basicpay
Customer : cust_id, cust_name, cust_address, cust_phone
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 7
Structure Initialization:

Like variables, structures can also be initialized at the compile time.

Syntax:
STRUCTURE_Variable = { value_1, value_2, ... , value_n };

Note: Individual structure members cannot be initialized within the template. Initialization is possible only
with the declaration of structure members.

Example:
struct student // student is called as structure “tag”
{
int rollno; // rollno & attendance are called as structure “members”
int attendance;
} s1={ 3001, 98 }; // s1 is called as structure “variable”

The above example assigns 3001 to the rollno and 98 to the attendance. Structure variable can be
initialized outside the function also.

Example:
struct student
{
int rollno;
int attendance;
};
struct student s1={ 3001, 98 };
struct student s2={ 3002, 97 };

Accessing Structure Members:


There are many ways for storing values into structure variables. The members of a structure can be
accessed using a “dot operator” or “period operator”.

Syntax
STRUCTURE_Variable . STRUCTURE_Member

E.g.
b1.author where, b1 - is a structure variable and
author - is a structure member

The different ways for storing values into structure variable is given below:

Method 1: Using Simple Assignment Statement b1.pages = 786;


b1.price = 786.50;

Method 2: Using strcpy() function strcpy(b1.title, “Programming in C”);


strcpy(b1.author, “John”);

Method 3: Using scanf() function scanf(“%s”, b1.title);


scanf(“%d”, &b1.pages);

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 8
Example 1:
#include<stdio.h>
struct book
{
int bookid;
char bookname[30];
char author[25];
float price;
int year;
int pages;
char publisher[25];
};
int main()
{
struct book b1;
printf("Enter the Book Id: ");
scanf("%d", &b1.bookid);
printf("Enter the Book Name: ");
scanf("%s", b1.bookname);
printf("Enter the Author Name: ");
scanf("%s", b1.author);
printf("Enter the Price: ");
scanf("%f", &b1.price);
printf("Enter the Year: ");
scanf("%d", &b1.year);
printf("Enter the Total No. of Pages: ");
scanf("%d", &b1.pages);
printf("Enter the Publisher Name: ");
scanf("%s", b1.publisher);

printf(“Entered Book Details are: “);


printf("%d %s %s %4.2f %d %d %s", b1.bookid, b1.bookname, b1.author, b1.price,
b1.year, b1.pages, b1.publisher);
return(0);
}

Output:
Enter the Book Id: 1002
Enter the Book Name: C_Programming
Enter the Author Name: John_Doe
Enter the Price: 123.50
Enter the Year: 2015
Enter the Total No. of Pages: 649
Enter the Publisher Name: Tata_McGraw

Entered Book Details are:


1002 C_Programming John_Doe 123.50 2015 649 Tata_McGraw

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 9
Arrays of Structures:
An array of structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store information
about multiple entities of different data types. The array of structures is also known as the collection of
structures.

Example 2: C program to define an array of structures that stores information of 5 students and prints it.

#include<stdio.h>
struct student
{
int rollno;
char name[25];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0; i<5; i++)
{
printf("\nEnter Rollno: ");
scanf("%d", &st[i].rollno);
printf("\nEnter Name: ");
scanf("%s", st[i].name);
}
printf("\nStudents Information List:");
for(i=0; i<5; i++)
{
printf("\nRollno: %d, Name: %s", st[i].rollno, st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students Enter Rollno: 4 Student Information List:
Enter Rollno: 1 Enter Name: v yamini Rollno: 1, Name: k nithyasree
Enter Name: k nithyasree Enter Rollno: 5 Rollno: 2, Name: V Murali
Enter Rollno: 2 Enter Name: v poojitha Rollno: 3, Name: c v jagadeesh
Enter Name: V Murali Rollno: 4, Name: v yamini
Enter Rollno: 3 Rollno: 5, Name: v poojitha
Enter Name: c v Jagadeesh
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 10
Structures within structures: (or) [ Nested Structures ]
Definition:

Structure can be defined inside another structure. i.e., Structures can also be nested. (or)

Nested structure in C is a structure within structure. One structure can be declared inside another
structure in the same way structure members are declared inside a structure. (or)

Nested structure in C is a structure that contains one or more members that are themselves structures.

Declaration in 2 ways:
1) By separate nested structure: 2) By embedded nested structure:
#include<stdio.h> #include<stdio.h>
struct date struct account
{ {
int day; int acc_no;
int month; char acc_type;
int year; char name[25];
}; float balance;
struct account struct // Here, date tag – may / mayn’t present
{ { // called as Empty tag.
int acc_no; int day;
char acc_type; int month;
char name[25]; int year;
float balance; } lastpayment;
struct date lastpayment; };
};
struct account cust1; int main()
{
int main() struct account cust1 = { 101, ‘S’, "Samba",
{ 5310.25, { 31, 03, 2023 } };
struct account cust1 = { 101, ‘S’, "Samba", printf("Entered account Details are: ");
5310.25, { 31, 03, 2023 } }; printf("%d %c %s %6.2f %d-%d-%d", cust1.acc_no,
printf("Entered account Details are: "); cust1.acc_type, cust1.name, cust1.balance,
printf("%d %c %s %6.2f %d-%d-%d", cust1.acc_no, cust1.lastpayment);
cust1.acc_type, cust1.name, cust1.balance, return(0);
cust1.lastpayment); }
return(0);
}

Output: Output:

Entered account Details are: Entered account Details are:


101 S Samba 5310.25 31-3-2023 101 S Samba 5310.25 31-3-2023

Note : printf() can also be written as, Note : Empty structure tag name is permissible only in
embedded nested structure.
printf("%d %c %s %6.2f %d-%d-%d", cust1.acc_no,
cust1.acc_type, cust1.name, cust1.balance,
cust1.lastpayment.day, cust1.lastpayment.month,
cust1.lastpayment.year);

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 11
UNIONS [ BASICS OF UNIONS ]
The concept of Union is borrowed from structure and the format are same as structure. The difference
between them is in terms of total memory space required to access its members.

Definition of Union:

"Union" is a composite data type that allows you to store different types of data in the same memory
location. Unlike structures, where each member has its own memory space, members of a union share the
same memory location. The size of a union is determined by the size of its largest member.

Declaration of Union:
Union can be declared as given below,
Syntax:
union <union-name>
{
data_type member-1;
data_type member-2;
--- --- ---
data_type member-n;
};
union <union-name> variable-1, variable-2, … … , variable-n;
• Union declaration always starts with uinon keyword. Here, union-name is known as tag.
• The union declaration is enclosed with in a, pair of curly braces.
• Each member of union may belong to different types of data.
• The individual members can be ordinary variables, arrays, pointers or other unions.

E.g. :
union account union account
{ {
int ac_no; int ac_no;
char ac_type; char ac_type;
(or)
char name[25]; char name[25];
float balance; float balance;
}; } oldcustomer, newcustomer;
union account oldcustomer, newcustomer;

Here union name is account. It contains four members.


• Members of union themselves do not occupy any space. Memory is allocated only after declaring union
variables.

Example for union:


Student : regno, student_name, age, address
Book : bookid, bookname, author, price, edition, publisher, year
Employee : employeeid, employee_name, age, sex, dateofbirth, basicpay
Customer : cust_id, cust_name, cust_address, cust_phone

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 12
Union Initialization:

Like variables, union can also be initialized at the compile time.

Syntax:
UNION_Variable = { value_1, value_2, ... , value_n };

Note: Individual union members cannot be initialized within the template. Initialization is possible only with
the declaration of union members.

Example:
union student // student is called as union “tag”
{
int rollno; // rollno & attendance are called as union “members”
int attendance;
} s1={ 3001, 98 }; // s1 is called as union “variable”

The above example assigns 3001 to the rollno and 98 to the attendance. Union variable can be
initialized outside the function also.

Example:
union student
{
int rollno;
int attendance;
};
union student s1={ 3001, 98 };
union student s2={ 3002, 97 };

Accessing Union Members:


There are many ways for storing values into union variables. The members of a union can be accessed
using a “dot operator ( . )” .or. “indirect membership operator ( -> )” / “arrow operator”

Syntax
UNION_Variable . UNION_Member

(or)

union <union-name> <union-variable>;


union <union-name> *ptr = &<union-variable>;
ptr -> union_member = value;

E.g.
ptr -> rollno = 14; where, ptr - is a pointer to specify the union
rollno - is a union member

The different ways for storing values into union variable is given below:

Method 1: Using Simple Assignment Statement b1.pages = 786;

Method 2: Using strcpy() function strcpy(b1.title, “Programming in C”);

Method 3: Using scanf() function scanf(“%d”, &b1.rollno);


scanf("%d", &(ptr -> rollno));
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 13
Example 1: Union program using dot operator (.) `

#include <stdio.h>
union MyUnion
{
int integer;
float floatingPoint;
char character;
};
int main()
{
union MyUnion data;
printf("Enter an integer: ");
scanf("%d", &data.integer);
printf("You entered: %d\n", data.integer);

printf("Enter a floating-point number: ");


scanf("%f", &data.floatingPoint);
printf("You entered: %.2f\n", data.floatingPoint);

printf("Enter a character: ");


scanf(" %c", &data.character);
printf("You entered: %c\n", data.character);
return 0;
}
Output:
Enter an integer: 101
You entered: 101
Enter a floating-point number: 125.75 all the members are getting printed very well because
You entered: 125.75 one member is being used at a time.
Enter a character: c
You entered: c

Note : If we attempt to print all the outputs together, we cannot print the correct outputs. Means, members of
a union share the same memory location. The size of a union is determined by the size of its largest member.
The values of integer and floatingPoint 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 character member
is getting printed very well.

#include <stdio.h>
union MyUnion
{
int integer;
float floatingPoint;
char character;
};
int main()
{
union MyUnion data;
printf("Enter an integer: ");
scanf("%d", &data.integer); Output:
printf("Enter a floating-point number: "); Enter an integer: 101
scanf("%f", &data.floatingPoint); Enter a floating-point number: 125.75
printf("Enter a character: "); Enter a character: c
scanf(" %c", &data.character); You entered: 1123778659
You entered: 125.75
printf("You entered: %.2f\n", data.floatingPoint); You entered: c
printf("You entered: %d\n", data.integer);
printf("You entered: %c\n", data.character);
Note: This union program approach produces a
return 0; wrong output.
}

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 14
Example 2: Union program using indirect membership operator ( -> ) / arrow operator `

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union employee
{
int empid;
char name[25];
char depart[15];
float salary;
};
union employee *emp = NULL;
int main()
{
emp = (union employee *) malloc( sizeof(union employee) );
printf("Employee Details: \n");
emp->empid = 101;
printf("Employee ID: %d\n", emp->empid);
strcpy(emp->name, "John Doe");
printf("Name: %s\n", emp->name);
strcpy(emp->depart, "Engineering");
printf("Department: %s\n", emp->depart);
emp->salary = 65000.00;
printf("Salary: %.2f\n", emp->salary);
free(emp); // Release dynamically allocated memory
return 0;
}

Output:
Employee Details:
Employee ID: 101
Name: John Doe
Department: Engineering
Salary: 65000.00

Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 15
Difference between Structure and Union in C:

Structure Union

1. It is declared using the struct keyword. It is declared using the union keyword.

2. Each variable member occupied a unique memory


All members share the same memory space.
space.
3. The size of the structure is determined by the sum The size of the union is determined by the size of its
of the sizes of its members. largest member.
4. Individual members can be accessed at a time
Only one member can be accessed at a time.
using the dot operator.
Members can be accessed by dot operator (.) and also
5. Members can be accessed by dot operator ( . )
arrow operator / indirect membership operator (->)
6. Example: Example:
struct student union student
{ {
int id; int id;
char name[25]; char name[25];
float avg; float avg;
} s1, s2, s3; } s1, s2, s3;

7. For above structure, memory allocation will be, For above union, the memory allocation will be based
int id - 02 Bytes on the size of the largest member because all
char name[25] - 25 Bytes members share the same memory space in a union.
float avg - 04 Bytes the largest member is the char name[25] array, which
Total memory allocation = 31 Bytes requires 25 Bytes (1 bytes x 25 = 25).
( 02 + 25 + 04 = 31 Bytes must require to access) Total memory allocation = 25 Bytes are enough.

(or)

The main differences between unions and structures can be summarized as follows:

Memory Allocation: Unions have members that share the same memory space, while structures have
separate memory space for each member.

Size: Unions have a size determined by the largest member, while structures have a size
determined by the sum of all members’ sizes.

Member Access: Only one member can be accessed at a time in a union, while structure members can be
accessed individually using the dot operator.

Initialization: Only the first member of a union can be explicitly initialized, whereas all members of
a structure can be initialized individually or collectively.

[Source: PROBLEM SOLVING AND PROGRAMMING (AK19) by Mr. V.SAMBASIVA, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE]
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 16

You might also like