C Unit 4
C Unit 4
C Unit 4
POINTER:
A pointer provides a way of accessing a variable without referring to the variable directly. A
pointer variable is a variable that holds the memory address of another variable. The pointer does not
hold a value. A pointer points to that variable by holding a copy of its address. It has two parts
1) the pointer itself holds the address
2) the address points to a value
Example
int a=5;
int* ptr;
ptr=&a;
About variable ―a:
1. Name of variable: a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory: 1025 (assume)
About variable ―ptr:
1. Name of variable: ptr
2. Value of variable which it keeps: 1025
3. Address where it has stored in memory: 5000 (assume)
Declaring Pointer:
The pointer operator a variable in C is ‘*’ called “value at address” operator. It returns the
value stored at a particular memory the value at address operator is also called “indirection” operator a
pointer variable is declared by preceding its name with an asterisk(*) .
Syntax: datatype *pointer_variable;
Where datatype is the type of data that the pointer is allowed to hold and pointer_variable is
the name of pointer variable.
Example:
int *ptr;
char *p;
float *p1;
Initializing Pointers:
Aditya Degree College, GWK - By Mohana Roopa 3
I B.SC - 2 Semester (‘C’ Language) UNIT-4
A pointer must be initialized with a specified address operator to its use. For example to
store the address of I in p, the unary & operator is to be used.
P=&I;
Sample program:
main()
{
int num=5;
int *ptr=#
printf(“the address num is %p”,&num);
printf(“the address num is %p”,ptr);
}
Benefits of using pointers are:-
1) Pointers are more efficient in handling arrays and data tables.
2) Pointers can be used to return multiple values from a function via function arguments.
3) The use of pointer arrays to character strings results in saving of data storage space in memory.
4) Pointers allow C to support dynamic memory management.
5) Pointers provide an efficient tool for manipulating dynamic data structures such as structures ,
linked lists , queues , stacks and trees.
6) Pointers reduce length and complexity of programs.
7) They increase the execution speed and thus reduce the program execution time.
we can use a pointer to point to an array, and then we can use that pointer to access the array
elements. Lets have an example,
#include <stdio.h>
int main()
{
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 a pointer and print all the values.
Pointers to two-dimensional arrays:-
Pointer can also be used to manipulate two-dimensional arrays.
Just like how x[i] is represented by
*(x+i) or *(p+i), similar, any element in a 2-d array can be represented by the pointer as follows.
*(*(a+i)+j) or *(*(p+i)+j)
The base address of the array a is &a[0][0] and starting from this address the complier allocates
contiguous space for all the element row – wise . i,e the first element of the second row is placed
immediately after the last element of the first row and so on
Ex:- suppose we declare an array as : int a[3][4]={{1,2,3,,4},{5,6,7,8},{9,10,11,12}};
The elements of a will be stored as shown below:
Drawbacks of pointers in c:
Uninitialized pointers might cause segmentation fault.
Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory
leak.
Pointers are slower than normal variables.
If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmers responsibility to use pointers effectively
and correctly.
Aim: To write a C-Program to read and print an employee data using structure.
Program:
#include<stdio.h>
struct Employee
{
int eno;
char ename[20];
Aditya Degree College, GWK - By Mohana Roopa 12
I B.SC - 2 Semester (‘C’ Language) UNIT-4
int esal;
};
void main()
{
struct Employee e;
clrscr();
printf("\nEnter Employee Number:");
scanf("%d",&e.eno);
printf("\nEnter Employee Name:");
scanf("%s",&e.ename);
printf("\nEnter Employee Salaray:");
scanf("%d",&e.esal);
printf("\n\nThe Employee Details are....\n");
printf("Employee Number:%d",e.eno);
printf("\nEmployee Name:%s",e.ename);
printf("\nEmployee Salary:%d",e.esal);
getch();
}
Array of Structures:
Array is a collection of similar data types. In the same way we can also define array of
structures. In this structure array, every element is of structure type. The array of structure is declared as
follows
Syntax: struct tagname
{
Data type member1;
Data type member2;
--------------------------
---------------------------
}array variable name[3];
Ex: struct emp
{
int eno;
char name[20];
float sal;
}e[10];
In the above example e[10] is an array of 10 elements containing 10 objects of type
structure. Each element of e[10] has structure type with three members that are eno,ename and
esal.
The following program illustrates the above concept.
Aim:
To Write a C-Program that creates a structure of 10 students having student number (sno),
student name (sname), marks in three subjects (m1,m2,m3), total marks of the students (tot) and
average (avg) and display the names of failed students.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
struct Student
{
int sno;
char sname[20];
Pointer to Structures:
Pointer is a variable can store the address of another variable .The variable may be of any data
type. In the same way we can also define pointer to structure. Here, starting address of the member
variables can be accessed. Thus, such pointers are called structure pointers.
Ex: Struct book
{
char name[25];
char author[25];
int pages;
};struct book *ptr;
In the above example *ptr is pointer to structure book. The syntax for using pointer with member is as
given below
1) ptr-> name 2) ptr -> author 3) ptr -> pages
{
-----------------------------------------
------------------------------------------
------------------------------------------
}
Example:
struct book
{
char name[20];
char author[20];
int pages;
}b1;
void main()
{
void show(struct book);//Prototype
---------
---------
show(b1);//Caller
---------
---------
}
void show(struct book b2)//Callee
{
-------
-------
}
Whenever a structure element is to be passed to any other function, it is essential to declare the
structure outside the main() function i.e., global.
The following program illustrates the above concept.
Aim: To write a C program to find the sum of two complex numbers.
Program:
#include<stdio.h>
#include<conio.h>
struct Complex
{
int real;
int img;
};
void f1(struct Complex x1,struct Complex x2)
{
struct Complex x3;
x3.real=x1.real + x2.real;
Aditya Degree College, GWK - By Mohana Roopa 15
I B.SC - 2 Semester (‘C’ Language) UNIT-4
x3.img=x1.img + x2.img;
printf("\n The Complex Sum is: %d+i%d",x3.real,x3.img);
}
void main()
{
struct Complex c1,c2;
clrscr();
printf("\nEnter the real and imag parts of first Complex Number:\n");
scanf("%d%d",&c1.real,&c1.img);
printf("\nEnter the real and img parts of second Complex Number:\n");
scanf("%d%d",&c2.real,&c2.img);
f1(c1,c2);
getch();
}
Unions:
A union is a user defined data type available in C that enables us to store different data types in
the same memory location. We can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory location
for multi-purpose.
Defining a Union
To define a union, we must use the union statement. The format of the union statement is
as follows:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Example:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in above example Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by character string.
Following is the example which will display total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result:
Memory size occupied by data : 20