0% found this document useful (0 votes)
2 views

UNIT 4 Pointers Userdefineddatatypes R23

This document provides an introduction to pointers and user-defined data types in C programming. It explains the concept of pointers, their benefits, declaration, initialization, and operations, including pointer arithmetic and dynamic memory allocation. Additionally, it covers how pointers can be used with arrays and the functions available for dynamic memory management.

Uploaded by

pavancharan576
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)
2 views

UNIT 4 Pointers Userdefineddatatypes R23

This document provides an introduction to pointers and user-defined data types in C programming. It explains the concept of pointers, their benefits, declaration, initialization, and operations, including pointer arithmetic and dynamic memory allocation. Additionally, it covers how pointers can be used with arrays and the functions available for dynamic memory management.

Uploaded by

pavancharan576
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/ 25

INTRODUCTION TO PROGRAMMING

UNIT – 4
POINTERS & USER DEFINED DATA TYPES
POINTERS
INTRODUCTION
A pointer is a derived data type in C, it is built from one of the
fundamental data types available in C. Pointers contain memory address
as their values.

“A pointer is a variable which contains the address of another


variable”.

WHY POINTERS (NEED OF POINTERS)


 Basically arrays are static. It means that the maximum possible size
of the array has to be declared before it’s use (i.e., at compile time). It
is not always possible to guess the maximum size of an array, because
for some applications we need the size of an array to be changed
during the program execution. This can be achieved by using the
pointers. Pointers allows memory allocation and de-allocation
dynamically.
 Pointers are used for establishing links between data elements or
objects for some complex data structures such as stacks, queues,
linked lists, binary trees and graphs.

BENEFITS TO THE PROGRAMMERS WITH POINTERS


 Pointers are more efficient in handling arrays and data tables.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
1
INTRODUCTION TO PROGRAMMING

 Pointers can be used to return multiple values from a function via


function arguments.
 Pointers permit reference to functions and there by facilitating passing
of functions as arguments to other functions.
 The use of pointer arrays to character string results in saving of data
storage space in memory.
 Pointers allow C to support dynamic memory management.
 Pointers provide an efficient tool for manipulating dynamic data
structures such as structures, linked lists, queues, stacks and trees.
 Pointers reduce length and complexity of programs.
 They increase the execution speed and reduce the program execution
time.
 With the help of pointers, variables can be swapped without physically
moving them.

DECLARATION OF POINTERS
The pointer is declared just like ordinary variables. They have to be
defined before they are used. The general form of a pointer declaration is as
follows:
data-type *Pointer_ Name

Here the “*” tells that variable Pointer _Name is pointer type variable.
i.e. it holds the address of another variable specified by the data-type.
Pointer_ Name needs a memory location. Pointer_ Name points to a variable
of type data_type.

Consider the following declaration.


int n=20;

This declaration tells the C compiler to:


1. Reserve space in memory to hold the integer value.
2. Associate the name with this memory location.
3. Store the value 20 at this location.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
2
INTRODUCTION TO PROGRAMMING

We may represent n’s location in the memory by the following memory


map:
n Location Name

20
Value at Location

2000 Location Address

Multiple pointers pointing to a variable

ACCESSING ADDRESS OF A VARIABLE (ADDRESS OPERATOR)


The address of the variable is not known immediately when the
variable is declared. We can determine the variable address by using an
operator called “address operator”. It is represented as “&”. The operator &
preceding the variable will return the address of the variable that is
associated with it.

Example:-
x=10;
p = &x;

Here let x is the variable whose value is 10 and suppose if its address
is 1000. Then address of x is 1000 which is returned to p.

ACCESSING A VARIABLE THROUGH ITS POINTER (DEREFERENCING


OPERATOR)
Once the pointer is assigned with the address of the variable now how
can we access the value of the variable using a pointer. It is done by using
an operator *. This operator is called value at address operator. The ‘value
at address’ operator is also called as ‘indirection’ operator. It is also called
as “dereferencing” operator.
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
3
INTRODUCTION TO PROGRAMMING

Example: -
int x, n, *p;
x = 10;
p = &x;
n = *p
/*PROGRAM TO PRINT ADDRESS AND THE VALUE OF A VARIABLE BY
USING ‘&’ AND ‘*’ OPERATORS */
#include< stdio.h>
main ()
{
int n=20;
printf (“address of n is: %u \n”, &n);
printf (“value of n is: %d \n”, n);
printf (“value of n is: %d”,*(&n));
}

In the first printf( ) statement ‘&’ is used it is C’s address of operator.


The expression &n returns the address of the variable n, which in this is
2000. The third printf( ) statement we used other pointer operator ‘*’ called
‘value at address’ operator. It returns the value stored at a particular
address. The ‘value at address’ operator is also called as ‘indirection’
operator. It is also called as “dereferencing” operator. The above program
says the value of *(&n) is same as n.

INITIALIZATION OF POINTER VARIABLES


The process of assigning the address of a variable to a pointer variable
is known as initialization. The initialized pointers will produce good results
otherwise they will produce error results. Once a pointer variable has been
declared we can use assignment operator to initialize the pointer variable.
Example: -
int x;
int *p
p = &x;

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
4
INTRODUCTION TO PROGRAMMING

If they are not initialized then they are left uninitialized as follows:

/* PROGRAM TO PRINT ADDRESS AND THE VALUE OF A VARIABLE BY


USING & AND * OPERATORS */
#include<stdio.h>
main ()
{
int n=20;
int *m;
m=&n;
clrscr( );
printf(“address of n is: %u \n”, &n);
printf(“address of m is:” %u\n”, m);
printf(“address of m is: %u\n”, &m);
printf(“value of n is: %d\n”,*(&n));
printf(“value of n is: %d”,*m);
}

POINTERS TO POINTERS
It is possible to make a pointer variable to point to another pointer
variable. Thus we can create a chain of pointers.
p2 p1 variable
address1 address2 value

Here the pointer variable p2 contains the address of pointer variable


p1 which points to the location that contains a value. This is known as
“multiple indirection”. A variable that is a pointer to a pointer must be
declared using an additional value at address operator in front of the name.
Example: -
int **p2;

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
5
INTRODUCTION TO PROGRAMMING

/* PROGRAM TO PRINT ADDRESS AND THE VALUE OF A VARIABLE BY


USING &, * AND **OPERATORS */
#include<stdio.h>
main ()
{
int n=20;
int *m;
int **p;
m=&n;
p=&m;
printf (“address of n is: %u \n “, &n);
printf (“address of n is: %u \n”, m);
printf ( “address of m is :%u \n”, &m);
printf (“address of m is: %u \n”, p);
printf (“address of p is: %u \n” &p);
printf (“value of m is: %u \n”, m);
printf (“value of p is: %u \n”, p);
printf (“value of n is: %d \n”, n);
printf (“value of n is: %d \n”,*(&n));
printf (“value of n is %d\n “, *m);
printf (“value of n is: %d \n”, **p);
}

POINTER AND ADDRESS ARITHMETIC


 As pointers contain address then we refer address arithmetic as
pointer arithmetic.
 The arithmetic operations performed on pointers is called pointer
arithmetic.
 The following operations on pointers can be performed
 Addition of a number to pointer is possible
 Subtraction of a number from a pointer is possible
 Subtraction of pointer from a pointer is possible
 Comparison of two pointers is possible
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
6
INTRODUCTION TO PROGRAMMING

 We can manipulate a pointer with postfix and unary


increment and decrement
 For example,
p+5 5+p p -5 p1 – p2 p++ --p
 The following operation do not work on pointers
 Addition of two pointers.
 Multiplying a pointer with a constant.
 Division of pointer with a constant.
p1 + p2 p1 * 5 p1 / 6

/* PROGRAM TO PERFORM POINTER ARITHMETIC */


#include<stdio.h>
main ( )
{
int i=5,*i1;
float j=5.8,*j1;
char k=’z’,*k1;
printf (“value of i=%d\n”, i);
printf (“value of j=%f\n”, j);
printf (“value of k=%c\n”, k);
i1=&i;
j1=&j
k1=&k;
printf (“the original value of i1 =%u\n”, i1);
printf (“the original value of j1=%u\n”, j1);
printf (“the original value of k1=%u\n”, k1);
i1++;
j1++;
k1++;
printf (“new value in i1=%u\n”, i1);
printf (“new value in j1=%u\n”j1);
printf (“new value in k1=%u\n”, k1);
}

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
7
INTRODUCTION TO PROGRAMMING

ARRAY MANIPULATION USING POINTERS (ARRAYS AND POINTERS)


When an array is declared, the compiler allocates a base address and
sufficient amount of memory to contain all the elements of the array in
continuous memory locations. The base address is the location of the first
element of the array denoted by a[0]. The compiler also defines the array
name as constant pointer to the first element.
Example: -
int a [5] = {1, 2, 3, 4, 5};

Here if the base address is 1000 for “a” and integer occupies 2 bytes
then the five elements requires 10 bytes as shown below.
Element a[0] a[1] a[3] a[4] a[5]
Value 1 2 3 4 5

Address 1000 1002 1004 1006 1008

The name of the array is “a” and it is defined as a constant pointer


pointing to the first element of the array and it is a[0] whose base address is
1000 becomes the value of ”a”. It is represented as
a = &a[0] = 1000;

If p is a pointer of integer type then p to point the array a is given by the


assignment statement
p = a;
which is equivalent to
p = &a[0];

Now it is possible to access every value of a using p++ to move from


one element to another element as
P = &a[0] =1000
P+1 = &a[1] = 1002
P+2 = &a[2] = 1004
P+3 = &a[3] = 1006
P+4 = &a[4] = 1008

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
8
INTRODUCTION TO PROGRAMMING

The address of the element is calculated by using the formula


address of a[3] = base address + (3 * scale factor of int)

When handling arrays we can use pointers to access the array


elements. Hence *(p+3) gives the value of a[3].

DYNAMIC MEMORY ALLOCATION


 There are two types of memory allocations: static allocation and
dynamic allocation
 Static allocation refers to allocation of memory for a variable at
compile time. They need declarations and definitions specified in the
source program. The number of bytes reserved cannot be changed.
 Dynamic allocation refers to allocation of memory for a variable at run
time. They use predefined functions to allocate and de-allocate
memory for data while the program is running. Memory is allocated
from heap through pointer.
 We use stdlib.h header file for our program when we dynamic memory
allocation functions.

DYNAMIC MEMORY MANAGEMENT


Consider an array
int marks [100];
Such a declaration would typically be used 100 student’s marks are to
be stored in memory. The moment we make declaration, 200 bytes are
reserved in memory for storing 100 integers in it. However it may so
happens that when we actually run the program we might be interested in
storing only 30 students’ marks, which would result in wastage of memory.

Other way round there always exists a possibility that when you run
the program you need to store more than 100 students’ marks, in this case
the array would fall short in size. Moreover there is no way to increase or
decrease the array size during execution, this is done by dynamic data
structures along with dynamic memory management techniques.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
9
INTRODUCTION TO PROGRAMMING

DYNAMIC MEMORY ALLOCATION FUNCTIONS


The process of allocating memory at run time is known as dynamic
memory allocation. The C programming does not have this function. But it
offers it through memory management functions. The memory management
functions are used to allocate and de-allocate storage during program
execution. The functions are
1. malloc 2. calloc
3. free 4. realloc

Memory Allocation Process


The storage for a C program is shown below:

Local Variables
Stack
Free Memory Heap
Global Variables
Permanent Storage Area
C Program Instructions

STORAGE OF A C PROGRAM
The program instructions and the global variables as well as the static
variables are stored in the region known as permanent storage area. The
local variables are stored in the in the area called stack. The memory space
between these two is the free area called heap.

The allocation or de-allocation of the space takes place from the heap.
Therefore the size of the heap increases or decreases depending on the
allocation and de-allocation of variables. If there is no space for allocation
then the functions return NULL.

malloc()
This function is used to allocate one block of storage. It reserves the
size specified by the pointer and returns void. The syntax for malloc is as
follows
ptr = (cast-type *) malloc (byte-size);
or
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
10
INTRODUCTION TO PROGRAMMING

void * malloc(size_t size);

Example: -
x = (int *) malloc (100 * sizeof(int));
It is also used to allocate storage for complex data such as structures.

calloc()
This function is used to allocate multiple blocks of memory. It is used
to store run time data types such as arrays and structures. It allocates
storage for multiple blocks and initializes them all to zero and the pointer
will point to the first byte of the first block. Here all blocks are same size.
The syntax is as follows:
ptr = (cast-type *) calloc (n, element-size);
or
void * calloc(size_t element_count, size_t element_size);

Example: -
x = (int *) calloc(n, sizeof(int));
free()
Compile time storage is allocated when the variable is declared with
storage class. But with dynamic storage we need to allocate storage
depending on the free storage because storage is limited. Whenever we are
not in need of the variable for which the storage is allocated then such
variables storage is removed. It is done by using free function. The syntax is
as follows:
free (ptr);
or
void free(void *ptr);
realloc()
Reallocation is done when
1. Storage is allocated to a variable is not sufficient so to modify the
variable’s storage.
2. If the storage is allocated more than the required storage then also we
need to alter the storage.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
11
INTRODUCTION TO PROGRAMMING

The process that is carried in the above two statement is called


reallocation.
Example: -
ptr = malloc (size);
ptr = realloc ( ptr, newsize);
or
void * realloc(void *ptr, size_t newsize);

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
12
INTRODUCTION TO PROGRAMMING

USER DEFINED DATA TYPES


STRUCTURES AND UNIONS
STRUCTURE
“A structure is defined as a collection of dissimilar data types
under one single name”.
or
“A structure is defined as heterogeneous collection of data items
specified under a single name”.
or
“A structure is defined as collection of elements of different data
types”.

DECLARATION OF STRUCTURE
 There are two ways of declaring a structure. They are listed as follows:
 Tagged structure
 Type declaration structure

1. Tagged Structure
 A tagged structure is used to define variables, parameters and return
types.
 The format is as follows
struct tag_name
{
data type member 1;
data type member 2;
data type member 3;
.
.
.
data type member n;
};
Example: -
struct book_bank

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
13
INTRODUCTION TO PROGRAMMING

{
char title[25];
char author[20];
int pages;
float price;
};

2. Type declaration with typedef


 Use the type definition to declare a structure is called type declaration
structure.
 We use the keyword tyedef here.
 The syntax is
typedef struct
{
data type member 1;
data type member 2;
data type member 3;
.
.
.
.
.
data type member n;
}tag_name;

Example: -
typedef struct
{
char title[25];
char author[20];
int pages;
float price;
}book_bank;

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
14
INTRODUCTION TO PROGRAMMING

DECLARING STRUCTURE VARIABLES


After defining the structure format we declare variables of the
structure data type. A structure variable declaration is similar to that of an
ordinary variable declaration. It includes
 Struct keyword
 Structure tag name
 List of variables separated by commas
 A terminating semicolon

Example: -
struct book_bank book1, book2, book3;

Here book1, book2, book3 are the structure variables of type struct
book_bank. Each of these variables can have the four members of the
structure book_bank. Then it is

struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
};
Struct book_bank book1, book2, book3;

or
struct book_bank
{
char title[25];
char author[20];
int pages;
float price;
} book1, book2, book3;

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
15
INTRODUCTION TO PROGRAMMING

ACCESSING STRUCTURE ELEMENTS / MEMBERS


The members of structure themselves are not variables. The members
should be linked to the structure variable in order to make them meaningful
members.

The link between a member and a variable are established using an


operator “.” which is also known as dot operator or period operator or
member operator.

Example: -
book2.price is the variable representing the price of book2 and can be
treated like any other ordinary variables.

STRUCTURE INITIALIZATION
Like other data type variables we can also initialize a structure
variable. However a structure must be declared as static.
int main(void)
{
static struct
{
int age;
float height;
} student = {20, 180.75};
………………
………………
}
This assigns the value 20 to student.age and 180.75 to
student.height. Suppose you want to initialize more than one structure
variable:
int main(void)
{
struct st_record
{
int age;
Dr. Ratna Raju Mukiri Ph.D.,
Dept. of CSE, SACET.
16
INTRODUCTION TO PROGRAMMING

float height;
};
static struct st_record student1={20,180.75};
static struct st_record student2={22,177.25};
…………………..
}

Another method is to initialize a structure variable outside the


function.
struct st_record
{
int age;
float height;
} student1 = {20, 180.75};
int main(void)
{
static struct st_record student2={22, 177.25};
………..
}
Example Program
#include<stdio.h>
#include<conio.h>
struct personal
{
char name[20];
int day;
char month;
int year;
float salary;
};
int main(void)
{
struct personal person;

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
17
INTRODUCTION TO PROGRAMMING

clrscr();
printf(“ Enter a person details:\n\n”);
printf(“ Enter person name : “);
scanf(“%s”,person.name);
printf(“Enter a person joining day : “);
scanf(“%d”,&person.day);
printf(“Enter a person joining month: “); scanf(“%d”,&person.month);
printf(“Enter a person joining year: “); scanf(“%d”,&person.year);
printf(“Enter a person salary: “);
scanf(“%d”,&person.salary);
printf(“\n\n persons name is : %s\n”,person.name);
printf(“\n\n persons joining day is : %s\n”,person.day);
printf(“\n\n persons joining month is : % s \ n ” , person. month );
printf(“\n\n persons joining year is : %s\n”,person.year);
printf(“\n\n persons salary is : %s\n”,person.salary);
return 0;
}

ARRAYS WITHIN STRUCTURES


C permits the use of array as structure member. We can use single or
multi-dimensional array of type int or float.
struct marks
{
int sub[3];
int total;
};
struct marks student[2];
In the above structure, the member sub contains three elements such
as sub[0], sub[1] and sub[2].These elements can be accessed by using the
subscripts. For example student[0].sub[2], indicates the marks obtained by
student 1 and third subject.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
18
INTRODUCTION TO PROGRAMMING

/*WRITE A PROGRAM TO CALCULATE THE SUBJECT-WISE AND


STUDENT-WISE TOTALS AND STORE AS A PART OF THE STRUCTURE*/
#include<stdio.h>
struct marks
{
int total;
int sub[3];
};
int main(void)
{
int i,j;
struct marks student[3]={{45,67,81,0},{75,53,69,0},{57,36,71,0}};
struct marks total;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
student[i].total=student[i].total+student[i].sub[j];
total.sub[j]=total.sub[j]+student[i].sub[j];
}
total.total=total.total+student[i].total;
}
printf(“ STUDENT TOTAL \n\n”);
for(i=0;i<3;i++)
printf(“ stu[%d]: %d\n”,i+1,student[i].total);
printf(“ SUBJECT TOTAL\n\n”);
for(j=0;j<3;j++)
printf(“subject=%d”, total.sub[j]);
printf(“\n Grand total : %d\n”, total.total);
return 0;
}

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
19
INTRODUCTION TO PROGRAMMING

ARRAYS OF STRUCTURES
We may declare an array as structures, where each element of the
array representing a structure variable. For example:
struct class student[100];

Defines an array called ‘student’ that consists of 100 elements. Each


element is defined to be of the type struct class. Consider the following
declaration
struct marks
{
int sub1;
int sub2;
int sub3;
};
int main(void)
{
struct marks student[3]={ {45,76,87},{78,68,79},{34,23,14} };
}

The above declaration shows the student as an array of three elements


student[0],student[1],student[2] and initializes their members as follows
student[0].sub1=45;
student[0].sub2=76;
.
.
.
.
student[2].sub3=14;
student[0].sub1 45
student[0].sub2 76
student[0].sub3 87
student[1].sub1 78
student[1].sub2 68

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
20
INTRODUCTION TO PROGRAMMING

student[1].sub3 79
student[2].sub1 34
student[2].sub2 23
student[2].sub3 14

An array of structures is stored inside the memory in the same way as


multi dimensional arrays. The array student is as above.

/*WRITE A PROGRAM TO CALCULATE THE SUBJECT-WISE AND


STUDENT-WISE TOTALS AND STORE AS A PART OF THE STRUCTURE*/
#include<stdio.h>
struct marks
{
int total;
int sub1;
int sub2;
int sub3;
};
int main(void)
{
int i;
struct marks student[3]={{45,67,81,0},{75,53,69,0},{57,36,71,0};
struct marks total;
for(i=0;i<3;i++)
{
student[i].total=student[i].sub1+student[i].sub2+student[i].sub3;
total.sub1=total.sub1+student[i].sub1;
total.sub2=total.sub2+student[i].sub2;
total.sub3=total.sub3+student[i].sub3;
total.total=total.total+student[i].total;
}
printf(“ STUDENT TOTAL \n\n”);
for(i=0;i<3;i++)

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
21
INTRODUCTION TO PROGRAMMING

{
printf(“ stu[%d]: %d\n”,i+1,student[i].total);
printf(“ SUBJECT TOTAL\n\n”);
printf(“sub1:%d\nsub2:%d\nsub3:%d\n”,total.sub1,
total.sub2, total.sub3);
printf(“\n Grand total : %d\n”,total.total);
}
return 0;
}

POINTERS TO STRUCTURES
The way we can have a pointer pointing to an int, or a pointer pointing
to a char, similarly we can have a pointer pointing to the struct. Such
pointers are known as ‘structure pointers’.
/*EXAMPLE PROGRAM ON STRUCTURE POINTERS*/
#include <stdio.h>
int main(void)
{
struct book
{
char title[25];
char author[25];
int no;
};
struct book b={“SHREETECH C Notes”,”srinivas”,102};
struct book *ptr;
ptr=&b;
printf(“%s %s %d\n”, b.title, b.author, b.no);
printf(“%s %s %d\n”, ptr->title, ptr->author, ptr->no);
return 0;
}
The first printf() is as usual. The second printf() however is peculiar.
We cannot use ptr.title, ptr.author and ptr.no because ptr is not a structure

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
22
INTRODUCTION TO PROGRAMMING

variable but a pointer to a structure, and the dot operator requires a


structure variable on its left. In such cases C provides an operator “->”
called an arrow operator to refer the structure elements.

UNIONS
Unions are a concept borrowed from structures and therefore follow
the same syntax as structures. The major difference between them is in
terms of storage. In structures each member has its own storage location,
whereas all the members of a union use the same location. It can handle
only one member at a time.

Declaration of Union
General Format
union name
{
type var1;
type var2;
.
.
.
};

Ex:
union item
{
int m;
float x;
char c;
}code;

This declares a variable code of type union item. The union contains
three members each with a different data type. However we can use only one
of them at a time. This is due to the fact that only one location is allocated
for a union variable, irrespective of its size.

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
23
INTRODUCTION TO PROGRAMMING

65497 65498 65499 65500

c
The compiler allocates a piece of storage that is large enough to hold
the largest variable type in the union. In the declaration above the member x
requires 4 bytes which is the largest among the members. The above figure
shows how all the three variables share the same address.

ACCESSING UNION
To access a union member we can use the same syntax that we used
for the structure members. The operator is member operator indicate by “. “

Ex:
code.m;
code.x;

INITIALIZATION OF UNIONS
 The union is initialized such that only the first type declared in the
union when the variable is declared
 The other types can be initialized by assigning values by reading
 When intializing, we must enclose the values with a set of braces even
if there is one value

DIFFERENCE BETWEEN STRUCTURES AND UNIONS


Structure Union

It is User defined data type It is Derived data type

Heterogeneous collection of Elements with different data


elements types
It begins with the keyword
It begins with the keyword struct
union

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
24
INTRODUCTION TO PROGRAMMING

struct tag_name union tag_name


{ {
datatype member1; datatype member1;
“ “
}; };

The structure variables are The union variables are declared


declared as as
struct tag_name variables union tag_name variables
struct student s1,s2; union student s1,s2;

struct student union student


{ {
int rollno; int rollno;
char stname[30]; char stname[30];
float per; float per;
} }

The members of the structure are The members of the union are
accessed by using dot operators accessed by using member
as s1.rollno, s2. Per operators as s1.rollno, s2. per

The structure is initialized as The union is initialized as


struct student union student
{ {
int rollno; int rollno;
char stname[30]; char stname[30];
float per; float per;
}; };
static struct student static union student
s1={101,"ram", 75.2}; s1={101,"ram", 75.2};

At a time we can access the all At a time only one member of


members of the structure union can be accessed

Only the largest member is


Every member of the structure is
considered for allocation of
allocated memory
memory for entire union

It requires more memory It requires less memory

Dr. Ratna Raju Mukiri Ph.D.,


Dept. of CSE, SACET.
25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy