Unit III-Programming in C
Unit III-Programming in C
UNIT III
POINTER
INTRODUCTION
A pointer is a derived data type in C. It is built from one of the fundamental datatypes available in
C. Pointers contains the memory address as their values. Memory addresses are the location in the
computer where program and data are stored.
Memory Organization
A = 10
65535
Whenever we declare a variable, the system allocates an appropriate memory location to hold the
value of the variable.
Consider the following statement int A =10 where A is a variable, 10 is the value and 65535 is
the memory address. Since the memory address are the numbers they can be assigned to variable,
such variables are called pointer variable or pointer.
DECLARATION OF POINTER
Pointer should be declared before use them
Syntax: Data type *pointer name;
Asterisk (*) tells that variable is a pointer. Pointer name is a user defined identifier
points to variable of type datatype.
Ex: int *p;
Here p is pointer variable that points to integer datatype
When pointer declared, it contains garbage value i.e. it may point any value in the memory.
INITIALIZATION OF POINTER
The process of assigning the address of variable to a pointer variable is known as initialization.
Syntax: Pointer = & variable;
Where & is the address operator.
Ex: int a;
int *p;
p = &a;
Note: 1. float q;
int *p;
p = &q; //Wrong
Trying to assign address of float variable to integer pointer leads to error.
The first line declares q and r as integer variable and p as pointer variable. The 2nd line assigns the
values 30 to q and 3rd line assigns address of q into p. The 4th line contains the * operator, when *
is placed before pointer then pointer return the values of variable. 5th line tells pointer value is
assigned to r variable.
OUTPUT
u1= 16, u2 = 16
Program to illustrate use of * operator to access the values of variable through pointer.
#include <stdio.h>
void main( )
{
int x, y;
int *ptr;
x = 10;
ptr = &x;
y = *ptr;
printf("\nThe value of x = %d\n", x);
printf("%d is stored at address %u\n”, x, &x);
printf("%d is stored at address %u\n”, *8x, &x);
printf("%d is stored at address %u\n”, *ptr, ptr);
printf("%u is stored at address %u\n”, ptr, &ptr);
printf("%d is stored at address %u\n”, y &y);
*ptr =25;
printf("\n Now value of x = %d\n", x);
getch();
}
OUTPUT
The value of x = 10
10 is stored at address 65524
10 is stored at address 65524
10 is stored at address 65524
65524 is stored at address 65522
10 is stored at address 65520
Now value of x =25
POINTER TO POINTER
A Pointer address is stored in another pointer is called pointer to pointer.
Syntax: datatype **pointer variable;
Ex: int **p;
OUTPUT
value of x = 22
value of x through p = 22
value of x through p1 = 22
Consider the base address of num is 1000 and integer requires 2 bytes, the five element will be
stores as follows.
If we declare P as an integer pointer then we can make pointer P to pint array num by using syntax.
Syntax: Pointer Variable = Array;
Ex: P = num;
Here P is pointer and num is the array.
Accessing every value of num using pointer P. P++ to move from one element to another. The
relationship between pointer and array are shown below.
P = &num[0];
P+1 = &num[1];
P+2 = & num [2];
P+3 = & num [3];
P+4 = & num [4];
we denote array elements as a num [i], where i is the index value. Similarly pointers can access
the array elements using the indirection operator (*).
*(P + i)
* is a dereferencing operator used to extract the value from the address (P + i).
P represents the pointer name and i represents the index value.
(P + i) will give the address of the array elements as the value of i changes from 0-4
Ex: #include<stdio.h>
int main()
{
int num[5] = {10, 20, 30, 40, 50};
int *P , i;
P = num;
for(i = 0; i < 5; i++)
printf("value stored in array = %d\n",*(P+i));
return 0;
}
OUTPUT
value stored in array = 10
value stored in array = 20
value stored in array = 30
value stored in array = 40
value stored in array = 50
{
printf("The array element is = %d \n", *ptr);
ptr ++;
}
getch();
}
OUTPUT
Enter the values of array
12345
The array element is = 1
The array element is = 2
The array element is = 3
The array element is = 4
The array element is = 5
POINTER ARITHMETIC
The pointer can be used in arithmetic operation like addition, subtraction, multiplication, division.
Ex:
#include <stdio.h>
void main()
{
int a, b, c;
int *r, *s;
a=90, b=30;
r = &a;
s = &b
c = *r + *s;
printf(“Addition =%d\n”, c);
c = *r - *s;
printf(“Subtraction =%d\n”, c);
c = *r / *s;
printf(“Division =%d\n”, c);
c = *r * *s;
printf(“Multiplication =%d\n”, c);
getch();
}
OUTPUT
Addition = 120
Subtraction =60
Division = 3
Multiplication = 2700
ADVANTAGES
DISADVANTAGES
If memory is allocated using pointer is not deallocate then it causes memory leakage.
Uninitialized pointer cause error in program.
Pointers are complicated to handle compared to variable.
A function is a sub programs with a set of statements that perform some specific task when it is
called.
Any ‘C’ program contain at least one function i.e main().
There are basically two types of function those are
1. Library function
Library functions are those functions which are already defined in C library, example printf(),
scanf(), strcat() etc. These are already declared and defined in C libraries.
FUNCTION DECLARATION
A general format of a function definition is to implement into two parts
1. Function header
2. Function body
Function header: It consists of three parts, the function type, Function Name and parameter list
where Function type is the data type of the function like int, char, double, float. Function name is
an identifier and it specifies the name of the function. The parameter list declares the type and
number of arguments that the function expects when it is called. Also, the parameters in the
parameter list receives the argument values when the function is called. These parameters are
called as formal parameters.
Function body: It contains the declarations and statement for performing the required task. The
body enclosed in braces, contains three parts. Local declaration that specify the variables needed
by the function. Executable statement that performs the task of the function. A return statement
that returns the value evaluated by the function.
The parameter that are used inside the function call are called actual parameter.
Formal parameter: The parameter which are used in function definition are called formal
parameter. These parameter are used to hold the values that are sent by the actual parameter of
calling function through the function call.
Ex: int add (int a, int b)
void Subtraction(float a, float b)
int multiply (int *a, int *b)
The parameter that are used inside the function are called formal parameter.
2. Function Call
A function can be called by the function name with list of actual parameters end with semicolon
is called function call. The compiler execute these functions when it is called.
Syntax: function (arg1,arg2,arg3);
Ex: addition(a,b,c);
Sub(20,30,40);
S = sum(a, b);
3. Return type
It is used to return value to the calling function. It can be used in two way as return or
return (expression); where return is the keyword having predefined meaning.
Ex: return a; // Returning the value of a to calling function
return (a*b); // Returning the value of expression a*b to calling function
return // Does not return any value.
4. Global Variables: Variables declare outside of any function. These are known throughout the
program and they will hold their value throughout the program’s execution.
Ex: int a, b; // Global variables
void main()
{
a=10, b=20;
add(a, b);
}
void add(int a, b)
{
pritnf(“%d%d”, a,b);
}
5. Local Variables: Variables that are declared inside a function are called local variables. Local
variables are not know outside their own code block. They will hold their value only inside
their function.
6. Function Prototype: All the function must be declare before they are used. This can be done
by function prototype. A function definition serves as its prototype.
Syntax: function type function Name (parameter list);
Ex: int addition (int a, int b);
Depending on weather parameter are present or not and weather a value is returned or not, a
function can be categorized into four as follows.
Calling {
Function multiply ();
}
void multiply()
{
int x, y, c;
Called
Function x=10, y=20;
c = x*y;
printf (“Multiplication is = %d”, c);
}
OUTPUT:
Multiplication is = 200
OUTPUT:
Multiplication is = 200
Ex: #include<stdio.h>
#include<conio.h>
void multiply (int x, int y);
void main()
{
Calling int a, b, c;
Function a = 20, b =30;
multiply (a, b);
}
void multiply(int x, int y)
{
int c;
Called
Function c = x*y;
printf (“Multiplication is = %d”, c);
}
OUTPUT:
Multiplication is = 600
OUTPUT:
Multiplication is = 600
Ex: #include<stdio.h>
#include<conio.h>
void swap(int a, int b);
void main()
{
int a, b;
clrscr();
printf("Enter value for a, b \n");
scanf("%d%d",&a,&b);
printf("Before SWAP a = %d, b = %d \n",a, b);
swap(a, b); Actual parameter value is passing
printf("After SWAP a = %d, b = %d \n",a, b);
getch();
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
OUTPUT:
Enter value for a, b
20 30
Before SWAP a = 20, b = 30
After SWAP a = 20, b = 30
Ex: #include<stdio.h>
#include<conio.h>
void swap(int *a, int *b);
void main()
{
int a, b;
clrscr();
printf("Enter value for a, b \n");
scanf("%d%d",&a,&b);
printf("Before SWAP a = %d, b = %d \n",a,b);
swap(&a,&b); Actual parameter address is passing
printf("After SWAP a = %d, b = %d \n",a,b);
getch();
}
void swap(int *a, int *b) Formal Pointer becomes pointer
{
int *temp;
*temp = *a;
*a = *b;
*b = *temp;
}
OUTPUT:
Enter value for a, b
20 30
Before SWAP a = 20, b = 30
After SWAP a = 30, b = 20
STRUCTURE DEFINITION
It is the logically related collection of dissimilar data types grouped together to form a single entity.
STRUCTURE DECLARATION
Syntax: struct structure name
{
data type member1;
data type member2;
………
………
data type member n;
};
Where struct is a keyword, Structure name defines the name of the structure defined by user. N
numbers of dissimilar data members can be defined inside the structure.
We can assign values to structure member and use scanf() function to give values.
Ex: scanf (“%s”, s1.name);
scanf (“%d”, &s1.Reg);
OUTPUT:
enter name, Reg, marks
Shruthi
16
67.4
students details are
Name = Shruthi
Reg. number = 16
Marks = 67.4
This assigns the value sona to s1.name , 12 to s1.Reg and 45.6 to s1.marks and so on.
Another method to initialize a structure variable inside the main function
struct student
{
char name[20];
int Reg;
float marks;
};
void main( )
{
struct student s1 = {sona”, 12, 45.6};
struct student s2 = {“rupa”, 14, 76.5};
------------------------------------
}
The order of values enclosed in the braces must match the order of member in the structure
definition.
It is permitted have a partial initialization but it should be at the end. The uninitialized members
will be assigned default value as zero for int, float, double and \0 for char and string.
ARRAY OF STRUCTURES
Suppose we want to maintain data base of 200 students, Array of structures is used. To declare
array of structure a structure variable is declare with array.
s1[0] . Id = 12
s1[1] . Id = 1
s1[2] . Id = 2
void main()
{
struct student s1[3] ={ {“Shruthi”, 12}, {“Anu”, 1}, {“Banu”, 2}};
int i;
printf(“The details of Students\n”);
for(i = 0; i < 3; i++)
{
printf(“Name = %s”, s[i] . name);
printf(“Id = %d”, s[i] . Id);
getch();
}
OUTPUT:
The details of Students
Name = Shruthi
Id = 12
Name = Anu
Id = 1
Name = Banu
Id = 2
Note: Another example program for array of structure Refer Lab program Part B – Program 10.
SIZE OF STRUCTURE
Size of structure can be find using sizeof() operator with structure variable name or structure name
with keyword.
ADVANTAGES OF STRUCTURE
1. Structure allows us to create user defined data-type which can store items with different
data types.
2. Structure Reduced complexity of program
3. It is very easy to maintain complex records by using single name.
4. Array of structure are used to store more records with similar types
DISADVANTAGES
1. Structure occupies memory space for each and every member.
2. Structure is slower because it requires storage space for all the data.
UNION
Union is derived data type contains collection of different data type or dissimilar elements. All
definition declaration of union variable and accessing member is similar to structure, but instead
of keyword struct the keyword union is used, the main difference between union and structure is
Each member of structure occupy the memory location, but in the unions members share memory.
Union is used for saving memory.
printf("Sub2=%f\n", m. sub2);
}
OUTPUT
enter marks
45 75.5
The details of marks
Sub1 = 45
Sub2 = 75.5
Note:
Ex:- struct student
{
int i;
char ch[10];
};
struct student s;
union student
{
int i;
char ch[10];
};
union student s;
Whereas the union occupies only 10 byte. The highest datatype size will be allocate for union.
Advantages:
1. It occupies less memory compared to structure
2. Union enables to hold data of only one data member.
Disadvantages:
1. Union can access only one member at a time.
2. All the union member cannot be initialized at once.
STRUCTURE UNION
The keyword struct is defined as a structure The keyword union is used to define a union.
The size of the structure is greater than or The size of union is equal to the size of largest
equal to the sum of size of its member. member.
Complier allocates unique memory for all the Memory allocated is shared by individual
structure members. members of the union.
Altering the value of a member will not affect Altering the value of any of the members will
other members of the structure. alter other member’s values.
Individual member can be accessed at a time Only one member can be accessed at a time.
All members of a structure can be initialized at Only the first member of the union can be
once. initialized
Ex: struct book Ex: union book
{ {
int book_id; int book_id;
char book_name[10]; char book_name[10];
}; };
struct book b; union book b;