Você está na página 1de 30

UNIT 4 [Structures and Unions]

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.

Syntax for defining or declaring or creating a union:-

union union_name or tag name

data type1 var1,var2,--------;

data type2 var1,var2,----------;

-------------------------------

--------------------------------

};

union- union keyword is used for defining the union.

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 definition must ends with semicolon (;).

Example for union definition:-

union student

int rno;

char name[20];

int m1,m2,m3;

};

Union variable declaration:-

 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 variable can be declared in 2 ways.

1. At the time of creating the union

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;

s1 and s2 are two union variables of union student type.

2.After creating the union

union union_name

datatype1 var1,var2;

datatype2 var1,var2;

------------------------

------------------------

};

union union_name union_variable1, union_variable2,……….. union_variablen;

Ex:- union student s1,s2;

sizeof structure and union:-

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;

printf("\nSize of structure is %d",sizeof(s));

printf("\nSize of union is %d",sizeof(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 member ship or dot (.) operator


2. Using arrow(->) operator

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.

1.Assigning the values:-

s1.rno=10;

s1.m1=90;

strcpy(s1.name,”ramu”);

2.Reading the values from keyboard:-

Syntax:- scanf(“format specifiers” ,&union_variable.member1, &union_variable.member2);

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.

1.Assigning the values:-

s1->rno=10;
s1->m1=90;

strcpy(s1->name,”ramu”);

2.Reading the values from keyboard:-

Syntax:- scanf(“format specifiers”, &union_variable->member1, &union_variable->


member2);

Ex:- scanf(“%d%d%d%d%s”,&s->rno,&s->m1,&s->m2,&s->m3,&s->name);

Ex1:- 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;

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);

Output:- rno=garbage value

Name=ramu

Union Initialization:- We can initialize the members of union in 2 ways.

1. Initializing the members of union in union definition itself.

Ex:- union student

int rno;
char name[20];

int total;

}s={10};

2. Initialzing members of the union at union variable declaration

Ex:- union student 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];

};

union student s={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

Distinguish between structures and unions:-

Structures Unions

1. Structure can be defined as a collection of 1. Union can be defined as a collection

Different data type elements. of different data type elements.

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.

Of a structure has its own memory location.

3.struct keyword is used to define structure. 3.union keyword is used to define union.

4.Syntax to define structure:- 4.Syntax to define union:-

struct structure name or tag name union union name or tag name

{ {

data type1 var1,var2,--------; data type1 var1,var2,--------;

data type2 var1,var2,----------; data type2 var1,var2,----------;

------------------------------- -----------------------------------

-------------------------------- -----------------------------------

}; };

5.Syntax to declare structure variable:- 5.Syntax to declare union variable:-

struct structure_name structure_variable; union union_name union_variable;

6.whenever a structure variable is declared 6.whenever a union variable is declared


then memory will be allocated for all the then memory will be allocated for the

Members of the structure. Largest member and remaining members


shares the same memory location.

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

Structure simultaneously. Union simultaneously i.e. we can access

Only one member at a time.

9.Several members of the structure can be 9.Only the first member of the union can

Initialized at a time . be initialized.

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

Accessed at the same time.

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.

Syntax:- typedef data_type user_defined_datatype;

Ex:-typedef int marks;

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];

};

typedef struct student s;


Now s becomes user defined data type. So using s we can declare structure variables.

s s1,s2,s3;

3.typedef can be used as a part of structure definition to create user defined data types.

Ex:- typedef struct student

int rno;

char name[20];

}s;

s s1,s2,s3;

Ex:- typedef struct

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.

To define an enumeration , keyword enum is used.

Syntax:- enum enum_name { const1, const2, ------------};

By default const1 is 0, const2 is 1and so on. We change default values of enum elements
during declaration.

C program to demonstrate enum

#include<stdio.h>

int main()
{

enum day {mon,tue,wed,thu=50,fri,sat,sum=100};

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 , declaration and initialization of a pointer


 Pointer to pointer
 Pointer arithmetic
 Pointer to array
 Pointer to string
 Dynamic memory allocation
 Command line arguments
 Preprocessor directives

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:-

 Pointers are mainly useful to implement dynamic memory allocation.


 To access the data more quickly.
 To execute the program more fastly.
 To utilize the memory more efficiently.

Declaration of a pointer variable:-

A pointer variable must be declared before they are used in the program.

Syntax to declare a pointer variable:-

data_type *pointer_variable;

The possible data types are char, int, float and double and void.

The two operators used in pointers are:


& - Address of operator or reference operator.
* - value at address operator/de-referencing operator/in directional operator.

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

Initialization of a pointer:- A pointer variable must be initialized before it is used in the


program.
Ex:- int a=10;
int *ptr;
ptr=&a;

C program to demonstrate pointer declaration, initialization and accessing the data.


#include<stdio.h>
int main()
{
int a=10;
int *ptr;
ptr=&a;
printf("\nValue of a is %d",a);
printf("\nValue of a is %d",*ptr);
printf("\nValue of a is %d",*(&a));
printf("\nValue of a is %d",*(*(&ptr)));
printf("\nAddress of a is %u",&a);
printf("\nAddress of a is %u",ptr);
printf("\nAddress of a is %u",*(&ptr));
return 0;
}

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.

Pointer arithmetic operations are:-

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

Invalid pointer arithmetic operations:-

1. Addition of 2 pointers
2. Multiplication of 2 pointes
3. Division of 2 pointers

Incrementing a pointer:- whenever a pointer is incremented then it points to its next


memory location.

Decrementing a pointer:- whenever a pointer is decremented then it points to its previous


memory location.
Addition of a number to a pointer:- If a number is added to pointer variable then pointer
points to a new location after skipping N times size of the data type.

Ptr+N=ptr+(N*sizeof(pointer_variable));

For example, let ptr be a 4-byte integer , initially ptr pointing to location 5000.

Then ptr+5=5000+(5*4)=5200. Now ptr points to memory location 5200.

Subtraction of a number from a pointer:- If a number is subtracted from pointer variable


then pointer points to a new location before current location by N times size of the data type.

Ptr+N=ptr-(N*sizeof(pointer_variable));

For example, let ptr be a 4-byte integer , initially ptr pointing to location 5000.

Then ptr-5=5000-(5*4)=4800. Now ptr points to memory location 4800.

Subtracting 2 pointers:-It gives the total number of elements between 2 pointers.

C program to demonstrate pointer arithmetic:-

#include<stdio.h>

int main()

int *ptr1,*ptr2,a,b;

ptr1=&a;

ptr2=&b;

printf("\nInitially ptr1 is %u",ptr1);

ptr1++;

printf("\nAfter incrementation ptr1 is %u",ptr1);

printf("\nInitially ptr2 is %u",ptr2);

ptr2--;

printf("\nAfter decrementation ptr2 is %u",ptr2);

ptr1=ptr1+5;

printf("\nNow ptr1 is %u",ptr1);

ptr2=ptr2-5;

printf("\nNow ptr2 is %u",ptr2);


printf("\nptr1-ptr2=%d",ptr1-ptr2);

return 0;

Output:-

Initially ptr1 is 65490

After incrementation ptr1 is 65492

Initially ptr2 is 65492

After decrementation ptr2 is 65490

Now ptr1 is 65502

Now ptr2 is 65480

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).

C Program to demonstrate pointer to pointer:-

#include<stdio.h>

int main()

int a=10,*ptr1,**ptr2,***ptr3;

ptr1=&a;

ptr2=&ptr1;
ptr3=&ptr2;

printf("\nvalue of a is %d",a);

printf("\nThrough ptr1 value of a is %d",*ptr1);

printf("\nThrough ptr2 value of a is %d",**ptr2);

printf("\nThrough ptr3 value of a is %d",***ptr3);

return 0;

Output:-

value of a is 10

Through ptr1 value of a is 10

Through ptr2 value of a is 10

Through ptr3 value of a is 10

Pointer to array or pointer with array:-

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.

The generalized form for using pointer with an array,


*(a+i)
is same as:
a[i]

C Program to demonstrate pointer to array:-

#include<stdio.h>

int main()

int *a,i,n;

printf("\nente size of the array");

scanf("%d",&n);

printf("\nenter elements of the array");

for(i=0;i<n;i++)

scanf("%d",a+i);

printf("\nelements of the array are\n");

for(i=0;i<n;i++)

printf("%d\t",*(a+i));

return 0;

Pointer to string:- Pointer can points to string also.

C program to print a string character by character using pointer

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.

/*C program to print a string using pointer.*/

#include <stdio.h>

int main()
{

char str[100];

char *ptr;

printf("Enter a string: ");

gets(str);

//assign address of str to ptr

ptr=str;

printf("Entered string is: ");

while(*ptr!='\0')

printf("%c",*ptr++);

return 0;

Output

Enter a string: This is a test string.

Entered string is: This is a test string.

Pointer to function:- call by reference

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.

Drawbacks or limitations of arrays:-

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.

4. If we allocate less memory than required it will creates a problem.

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.

a[0] a[1] a[2] a[3] a[4]

11 22 33 44 55 Let value=100

a[0] a[1] a[2] a[3] a[4] a[5]

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.

a[0] a[1] a[2] a[3] a[4]

11 22 33 44 55

a[0] a[1] a[2] a[3]

22 33 44 55

To overcome the above limitations of array we use “dynamic memory allocation”.

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.

To implement dynamic memory allocation 4 functions are used.

1.malloc( )

2.calloc( )

3.realloc( )

4.free( )

1.malloc( ):-

 This function allocates one block of memory.


 Malloc stands for memory allocation.
 malloc( ) allocates requested size in bytes and returns a pointer to the first element of
memory block.
 If memory is not allocated then malloc( ) returns NULL.
 malloc( ) accepts only one argument.
 The default initial values are garbage values.

Syntax:-

Pointer_variable=(data type *) malloc(byte size);

C program to demonstrate malloc( ):-

#include<stdio.h>

int main()

int *p,n,i;

printf("\nEnter size of the array");

scanf("%d",&n);

p=(int *) malloc(n*sizeof(int));

if(p==NULL)

printf("\nMemory is not allocated");

else

printf("\nenter elements of the array");

for(i=0;i<n;i++)

scanf("%d",p+i);

printf("\nelements of the array are");

for(i=0;i<n;i++)

printf("%d\t",*(p+i));

free(p);

return 0;

}
2.calloc( ):-

 It allocates contiguous (multiple) blocks of memory.


 calloc( ) allocates multiple blocks of memory and returns a pointer to the first block.
 If memory is not allocated then calloc( ) returns NULL.
 calloc( ) accepts 2 arguments.
 The default initial values are zero’s.

Syntax:-

Pointer_variable=(data type *) calloc(no of blocks , block size);

C program to demonstrate calloc( ):-

#include<stdio.h>

int main()

int *p,n,i;

printf("\nEnter size of the array");

scanf("%d",&n);

p=(int *) malloc(n,sizeof(int));

if(p==NULL)

printf("\nMemory is not allocated");

else

printf("\nenter elements of the array");

for(i=0;i<n;i++)

scanf("%d",p+i);

printf("\nelements of the array are");

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.

Syntax:- pointer_variable=realloc(pointer_variable, new_size);

C program to demonstrate realloc( ):-

#include<stdio.h>

int main()

int *p,i;

p=(int *)malloc(6);

if(p==NULL)

printf("\nMemory is not allocated");

else

p[0]=11;

p[1]=22;

p[2]=33;

p=realloc(p,10);

p[3]=44;

p[4]=55;

printf("\nelements of the array are\n");

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);

Distinguish between malloc( ) and calloc( ):-

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:-

Ptr=(int *) malloc(10); ptr=(int *)calloc(5,2);

6.The return type of malloc( ) is void. 6.The return type of calloc( ) is void . So

So typecasting must be performed. Typecasting must be performed.

7.malloc( ) accepts only one argument 7.calloc( ) accepts 2 arguments i.e. no.of blocks

i.e. byte size. And block size.

8.Default initial values for malloc( ) 8.Default initial values for calloc( ) are zero’s

Are garbage values.

9.malloc( ) is faster than calloc( ). 9.calloc( ) is slower than malloc( ).


Command line arguments:- The arguments which are passed to the main( ) from command
prompt are known as “command line arguments”.

Here main( ) has 2 arguments.

1.argc(argument count):-It represents no. of arguments passed to the main( ) from


command prompt.

2.agv[ ](argument vector):-It is a pointer character array which points to each argument.

C program to demonstrate command line arguments:-

command.c

#include<stdio.h>

#include<conio.h>

int main(int argc,char *argv[])

int i;

printf("\nNo of arguments are %d",argc);

for(i=0;i<argc;i++)

printf("\nArgument is %s",argv[i]);

getch();

Result:-

Input:-

D:\TURBOC2>command welcome Mr.James Bond 007

Output:-

No of arguments are 5

Argument is command

Argument is welcome

Argument is Mr.James
Argument is Bond

Argument is 007

Preprocessor directives:-

 Before a C program is compiled in a compiler, source code is processed by a program


called preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and they begin with
“#” symbol.
Below is the list of preprocessor directives that C programming language offers.

Preprocessor directives are:-

1.File inclusion

2.Macro expansion

3.conditional compilation directives

4.Other pre-processor directives.

1.File inclusion:- The pre-processor directive #include is used to include header files in the
program.

Syntax:- #include <headerfile>

Ex:- #include <stdio.h>

2.Macro expansion:- Macro defines constant.

Syntax:- #define macro_name value

Ex:- #define PI 3.14

3.Conditional compilation directives:- To skip some of the statements in the program we


uses these directives.

#ifdef, #endif, #if, #else, #ifndef are conditional directives.

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

Ex1:-c program to demonstrate #ifdef, #else, #endif.

#include<stdio.h>

#define PI 3.14

int main()
{

#ifdef PI

printf("PI is defined");

#else

printf("PI is not defined");

#endif

return 0;

Output:- PI is defined

Ex2:-c program to demonstrate #ifndef, #else, #endif.

#include<stdio.h>

int main()

#ifndef PI

printf("PI is not defined");

#else

printf("PI is defined");

#endif

return 0;

Output:- PI is not defined

Ex3:-c program to demonstrate #ifndef, #else, #endif.

#include<stdio.h>

#define total 429

int main()

#if(total==429)
printf("PI is defined");

#else

printf("PI is not defined");

#endif

return 0;

Output:- PI is defined

4.Other pre-processor directives:-

1.#undefine:-Used to un define the defined macro

#undefine macro_name

2.#error:-Used to report or display error messages on the screen.

#error “message”

Você também pode gostar