Escolar Documentos
Profissional Documentos
Cultura Documentos
User defined data types are structures, unions, typedef and enum
Unions
Topics in Unions:-
Union definition
Union variable declaration
sizeof union
Accessing members of union
Examples
Union Initialization
Differentiate between structures and unions
typedef
enum
Union definition:- It is a user defined data type. Union can be defined as a collection of
heterogeneous (different) data type elements and all the members of the union share the same
memory location.
-------------------------------
--------------------------------
};
union name or tag name:- For union name identifier rules are to be followed. Union name
is nothing but name of the user defined data type.
data type:- The basic data types are int, float, char and double.
members:- The variables which are declared inside a union are known as members. The
members of union must be enclosed in curly braces { }.
union student
int rno;
char name[20];
int m1,m2,m3;
};
Whenever a union is defined then memory will not be allocated to the members of the
union.
For member variables the memory will be allocated only when a union variable is
declared.
So, whenever a union variable is declared then memory will be allocated for the
largest member and all the members of the union shares the same memory location.
Like normal variables the union variables are declared before they are used in the
program.
union union_name
datatype1 var1,var2;
datatype2 var1,var2;
------------------------
------------------------
}union_variable1, union_variable2,…………union_variablen;
Example:
union student
int no;
char name[20];
float avg;
}s1,s2;
union union_name
datatype1 var1,var2;
datatype2 var1,var2;
------------------------
------------------------
};
The sizeof structure is the sum of sizes of all members. The sizeof union is the size of largest
member size and all the members share same area.
Ex:-
#include<stdio.h>
int main()
struct student
int rno;
char name[10];
float avg;
}s;
union student1
int rno;
char name[10];
float avg;
}u;
return 0;
Output:-
Size of structure is 16
Size of union is 10
Accessing members of a union:- The members of a union can be accessed in 2 ways.
1.Using period or dot(.) operator:- If the union variable is an ordinary variable then we uses
dot(.) operator for accessing the members of union.
Syntax:- union_variable.member;
Ex:- s1.rno;
s1.name;
s1.m1;
Storing the values in the members of union:- We can store the values in the members
of union in 2 ways.
s1.rno=10;
s1.m1=90;
strcpy(s1.name,”ramu”);
Eg:- scanf(“%d%d%d%d%s”,&s1.rno,&s1.m1,&s1.m2,&s1.m3,&s1.name);
2.Using Arrow(->) operator:- If the union variable is pointer variable then we uses arrow
(->) operator for accessing the members of union.
Syntax:- union_variable->member;
Ex:- s1->rno;
s1->name;
s1->m1;
Storing the values in the members of union:- We can store the values in the members
of union in 2 ways.
s1->rno=10;
s1->m1=90;
strcpy(s1->name,”ramu”);
Ex:- scanf(“%d%d%d%d%s”,&s->rno,&s->m1,&s->m2,&s->m3,&s->name);
include<stdio.h>
#include<string.h>
int main()
union student
int rno;
char name[20];
};
union student s;
s.rno=10;
printf("\nrno=%d",s.rno);
strcpy(s.name,"ramu");
printf("\nName=%s",s.name);
Output:- rno=10
Name=ramu
Ex2:- C program to process student record using unions
#include<stdio.h>
#include<string.h>
int main()
union student
int rno;
char name[20];
};
union student s;
s.rno=10;
strcpy(s.name,"ramu");
printf("\nrno=%d",s.rno);
printf("\nName=%s",s.name);
Name=ramu
int rno;
char name[20];
int total;
}s={10};
Union initialization is done only for the first member but it’s not possible to initialize to all
the members simultaneously.
The initialization union student s={“ramu”} is not valid because the data type of first member
is int. Other members can be initialized by either assigning or reading from keyboard.
For example union student s={10,”ramu”,500} is not valid because all the members of the
union can’t be initialized simultaneously.
Ex:-
#include<stdio.h>
#include<string.h>
int main()
union student
int rno;
char name[20];
};
printf("\nRoll no is %d",s.rno);
strcpy(s.name,"ramesh");
printf("\nName=%s",s.name);
Output:-
Roll no is 20
Name is ramesh
Structures Unions
2. The members of structure are stored in 2.All the members of the union shares
Adjacent memory locations i.e. each member the same memory location.
3.struct keyword is used to define structure. 3.union keyword is used to define union.
struct structure name or tag name union union name or tag name
{ {
------------------------------- -----------------------------------
-------------------------------- -----------------------------------
}; };
7.size of structure is sum of all members sizes. 7.size of union is largest member size.
8.We can access all the members of the 8.We can’t access all the members of the
9.Several members of the structure can be 9.Only the first member of the union can
10. The usage of structure is efficient when all 10.Tthe usage of union is efficient when the
members are actively used in the program members of it are not required to be
11.Self referential structures can be implemented. 11.Self referential unions can’t be implemented.
typedef:-
1.typedef allows us to create alias(alternative) name or user defined data type for the
existing data type.
Now marks becomes int data type. So we can use marks for declaring int variables.
marks m1,m2,m3;
2.typedef can also be used to create a alias(alternative) name or user defined data type for the
existing data type.
struct student
int rno;
char name[20];
};
s s1,s2,s3;
3.typedef can be used as a part of structure definition to create user defined data types.
int rno;
char name[20];
}s;
s s1,s2,s3;
int rno;
char name[20];
}s;
s s1,s2,s3;
enum(enumerated data type):- enum is a user defined data type which consists of integer
constants.
By default const1 is 0, const2 is 1and so on. We change default values of enum elements
during declaration.
#include<stdio.h>
int main()
{
printf("\nMonday=%d",mon);
printf("\nTuesday=%d",tue);
printf("\nWednesday=%d",wed);
printf("\nThursday=%d",thu);
printf("\nFriday=%d",fri);
printf("\nSaturday=%d",sat);
printf("\nSunday=%d",sun);
return 0;
Output:-
Monday=0
Tuesday=1
Wednesday=2
Thursday=50
Friday=51
Saturday=100
UNIT 3 [Functions and Pointers]
Pointers
Topics in pointers:-
Definition of a pointer:-
Pointers are the special variables which are used to store the addresses of other variables of
the same data type.
By using int pointer we can store address of int variable likewise float pointer stores address
of float variable.
Uses of pointers:-
A pointer variable must be declared before they are used in the program.
data_type *pointer_variable;
The possible data types are char, int, float and double and void.
Ex1:- int *p; here p is a pointer variable which points to int variable.
Ex2:- float *p; here p is a pointer variable which points to float variable
Output:-
Value of a is 10
Value of a is 10
Value of a is 10
Value of a is 10
Address of a is 65494
Address of a is 65494
Address of a is 65494
Pointer arithmetic:- Like variables we can also performs arithmetic operations on pointers.
1. Incrementing a pointer
2. Decrementing a pointer
3. Addition of a number to a pointer
4. Subtraction of a number from pointer
5. Subtracting 2 pointers
1. Addition of 2 pointers
2. Multiplication of 2 pointes
3. Division of 2 pointers
Ptr+N=ptr+(N*sizeof(pointer_variable));
For example, let ptr be a 4-byte integer , initially ptr pointing to location 5000.
Ptr+N=ptr-(N*sizeof(pointer_variable));
For example, let ptr be a 4-byte integer , initially ptr pointing to location 5000.
#include<stdio.h>
int main()
int *ptr1,*ptr2,a,b;
ptr1=&a;
ptr2=&b;
ptr1++;
ptr2--;
ptr1=ptr1+5;
ptr2=ptr2-5;
return 0;
Output:-
ptr1-ptr2=11
Pointer to pointer:-
Generally pointer points to ordinary variable i.e. by using pointer variable we can
stores the address of ordinary variable.
Pointer can points to pointer also i.e. by using pointer we can stores address of
another pointer.
A single asterisk pointer(*ptr) points to ordinary variable i.e. A single pointer
variable(*ptr) is used to store the address of ordinary variable.
A double asterisk pointer(**ptr) points to a single pointer variable(*ptr) i.e. A
double asterisk pointer(**ptr) is used to store the address of single pointer
variable(*ptr).
A triple asterisk pointer(***ptr) points to a double pointer variable(**ptr) i.e. A
triple asterisk pointer(***ptr) is used to store the address of double pointer
variable(**ptr).
#include<stdio.h>
int main()
int a=10,*ptr1,**ptr2,***ptr3;
ptr1=&a;
ptr2=&ptr1;
ptr3=&ptr2;
printf("\nvalue of a is %d",a);
return 0;
Output:-
value of a is 10
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:
Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000. In short, arr has two
purpose - it is the name of an array and it acts as a pointer pointing towards the first element
in the array.
arr is equal to &arr[0] //by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to
another.
we can use a pointer to point to an Array, and then we can use that pointer to access the
array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int *p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in the array one by
one. We can also use the Base address (a in above case) to act as pointer and print all
the values.
#include<stdio.h>
int main()
int *a,i,n;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",a+i);
for(i=0;i<n;i++)
printf("%d\t",*(a+i));
return 0;
Here, we have two variables, str is a string variable and ptr is a character pointer, that will
point to the string variable str.
First of all, we are reading string in str and then assigning the base address of str to the
character pointer ptr by using ptr=str or it can also be done by using ptr = &str[0].
And, finally we are printing the string character by character until NULL not found.
Characters are printing by the pointer *ptr.
#include <stdio.h>
int main()
{
char str[100];
char *ptr;
gets(str);
ptr=str;
while(*ptr!='\0')
printf("%c",*ptr++);
return 0;
Output
Dynamic memory allocation:-When an array is declared then we must specify size of the
array at declaration because we can’t change size of the array during program execution.
If the memory is allocated at compilation time then it is called as “static memory allocation”.
Eg:- int a[5]; for this array a 10 bytes of memory will be allocated at compilation time.
1. We must know in advance regarding how many elements are to be stored in array.
2. Arrays uses static memory allocation i.e. memory will be allocated at compilation
time. So it’s not possible to change size of the array at run time.
3. Since array size is fixed, if we allocate more memory than required then memory
space will be wasted.
5. The main drawback of arrays is insertion and deletion operations are expensive.
6. For example to insert an element into the array at beginning position, we need to shift
all array elements one position to the right in order to store a new element at
beginning position.
11 22 33 44 55 Let value=100
100 11 22 33 44 55
7. For example to delete an element from the array at beginning position , we need to
shift all array elements one position to its left.
11 22 33 44 55
22 33 44 55
Dynamic memory allocation:- If the memory is allocated at run time or during execution
time of the program then it is called as dynamic memory allocation.
1.malloc( )
2.calloc( )
3.realloc( )
4.free( )
1.malloc( ):-
Syntax:-
#include<stdio.h>
int main()
int *p,n,i;
scanf("%d",&n);
p=(int *) malloc(n*sizeof(int));
if(p==NULL)
else
for(i=0;i<n;i++)
scanf("%d",p+i);
for(i=0;i<n;i++)
printf("%d\t",*(p+i));
free(p);
return 0;
}
2.calloc( ):-
Syntax:-
#include<stdio.h>
int main()
int *p,n,i;
scanf("%d",&n);
p=(int *) malloc(n,sizeof(int));
if(p==NULL)
else
for(i=0;i<n;i++)
scanf("%d",p+i);
for(i=0;i<n;i++)
printf("%d\t",*(p+i));
free(p);
return 0;
3.realloc( ):-It is used to change or modify the size of already allocated memory block.
This function copies the contents of original memory block to the modified memory block
without losing data.
#include<stdio.h>
int main()
int *p,i;
p=(int *)malloc(6);
if(p==NULL)
else
p[0]=11;
p[1]=22;
p[2]=33;
p=realloc(p,10);
p[3]=44;
p[4]=55;
for(i=0;i<5;i++)
printf("%d\t",p[i]);
}
free(p);
return 0;
4.free( ):- This function is used to destroy or release the previously allocated memory block.
Syntax:- free(pointer_variable);
malloc( ) calloc( )
1.It stands for memory allocation. 1.It stands for contiguous memory allocation.
2.It allocates only one block of 2.It allocates multiple blocks of memory.
Memory.
3.It allocates requested size in bytes and 3.It allocates multiple blocks of memory and
Returns a pointer to the starting address of returns a pointer to the first block.
the block.
4.syntax:- 4.syntax:-
Ptr=(data type *) malloc(byte size); Ptr=(data type *) calloc(no of blocks, block size);
5.Ex:- 5.Ex:-
6.The return type of malloc( ) is void. 6.The return type of calloc( ) is void . So
7.malloc( ) accepts only one argument 7.calloc( ) accepts 2 arguments i.e. no.of blocks
8.Default initial values for malloc( ) 8.Default initial values for calloc( ) are zero’s
2.agv[ ](argument vector):-It is a pointer character array which points to each argument.
command.c
#include<stdio.h>
#include<conio.h>
int i;
for(i=0;i<argc;i++)
printf("\nArgument is %s",argv[i]);
getch();
Result:-
Input:-
Output:-
No of arguments are 5
Argument is command
Argument is welcome
Argument is Mr.James
Argument is Bond
Argument is 007
Preprocessor directives:-
1.File inclusion
2.Macro expansion
1.File inclusion:- The pre-processor directive #include is used to include header files in the
program.
1.#ifdef:-
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes
the code.
Syntax:
#ifdef MACRO
//code
#endif
2. #ifndef:-
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code.
Syntax:
#ifndef MACRO
//code
#endif
3. #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code.
Syntax:
#if expression
//code
#endif
4. #else
The #else preprocessor directive evaluates the expression or condition if condition of #if is
false. It can be used with #if, #ifdef and #ifndef directives.
Syntax:
#if expression
//if code
#else
//else code
#endif
#include<stdio.h>
#define PI 3.14
int main()
{
#ifdef PI
printf("PI is defined");
#else
#endif
return 0;
Output:- PI is defined
#include<stdio.h>
int main()
#ifndef PI
#else
printf("PI is defined");
#endif
return 0;
#include<stdio.h>
int main()
#if(total==429)
printf("PI is defined");
#else
#endif
return 0;
Output:- PI is defined
#undefine macro_name
#error “message”