Unit-4 Intro To Prog (AK23)
Unit-4 Intro To Prog (AK23)
POINTERS: .
Introduction to Pointers:
In programming, a pointer is a variable that stores the memory address of another variable. Pointers
are used to work with memory directly and enable dynamic memory allocation and manipulation. To declare
a pointer, use the data type followed by an asterisk (*) and the name of the pointer variable.
You can initialize a pointer with the address of another variable. To access the value stored at the
memory address pointed to by a pointer, you use the dereference operator (*).
Pointers are commonly used for dynamic memory allocation, passing parameters to functions by
reference, and working with arrays and structures. Pointers are powerful but avoid issues like dereferencing
null pointers or accessing memory out of bounds.
Definition:
Pointer is defined as a derived data type that can store the address of another variable or a memory
location. (or)
Pointer is a variable which stores the address of another variable. This variable can be of type int, char,
array, function, or any other pointer. (or)
Pointer is a variable that stores the memory address of another variable as its value. A pointer variable
points to a data type (like int) of the same type, and is created with the * operator.
Example:
int n = 10;
int *p = &n; // variable p of type pointer is pointing to the address of the variable n of integer data type
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 1
Features of pointers:
Pointers are used frequently in c, as they offer a number of benefits to the programmers.
Pointer is a variable that stores the address of another variable. The dereference operator is also known
as an indirection operator, which is represented by (*). When indirection operator (*) is used with the pointer
variable, then it is known as dereferencing a pointer. When we dereference a pointer, then the value of the
variable pointed by this pointer will be returned.
Dereferencing is used to access or find out the data which is contained in the memory location which
is pointed by the pointer. The * (asterisk) operator which is also known as the C dereference pointer is used
with the pointer variable to dereference the pointer.
Address operator:
The Address Operator in C is a special unary operator that returns the address of a variable. It is denoted
as the Ampersand Symbol ( & ). This operator returns an integer value which is the address of its operand in
the memory.
Note: The memory address is printed using the “%p” format specifier in hexadecimal format.
#include <stdio.h>
int main()
{
int x = 9; // declare the integer variable x
int *ptr; // declare the integer pointer variable ptr
ptr = &x; // store the address of 'x' variable to the pointer variable 'ptr'
*ptr = 14; // change the value of 'x' variable by dereferencing a pointer 'ptr'
printf("value of x is: %d", x); // value of 'x' from 9 to 14 because 'ptr' points to 'x' location and
return 0; //dereferencing of 'ptr'
}
#include<stdio.h>
int main()
{
int u = 3;
int v;
int *pu;
int *pv;
pu = &u;
v = *pu;
pv = &v;
return(0);
}
Output:
u=3 &u=6684356 pu=6684356 *pu=3
Note:
pu is a pointer to u, and pv is a pointer to v. therefore pu represent the address of u, and pv represents
the address of v. The output shown above is, in the first printf we have printed the address of variables output
with unsigned integer (%u) , and in the Second printf the address of variables is printed with hexa decimal
values (%X).
#include<stdio.h>
int main()
{
int a = 25, b = 10, *p, *j;
p = &a;
j = &b;
printf("Addition a + b = %d \n", *p + b);
printf("Subtraction a – b = %d \n", *p - b);
printf("Multiplication a * b = %d \n", *p * *j);
printf("Division a / b = %d \n", *p / *j);
printf(" Modulo division a % b = %d \n", *p % *j);
return(0);
}
Output:
Addition a + b = 35
Subtraction a - b = 15
Multiplication a * b = 250
Division a /b = 2
Modulo division a % b = 5
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 3
Pointer and Address arithmetic: .
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The
pointer variables store the memory address of another variable. It doesn’t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C
pointer arithmetic operations are slightly different from the ones that we generally use for mathematical
calculations.
Example:
Data type Initial address Operation Address after operations Required bytes
int i = 2 4046 ++ -- 4048 4044 2 bytes
char c = ’x’ 4053 ++ -- 4054 4052 1 bytes
float f = 4.2 4058 ++ -- 4062 4054 4 bytes
long int l = 2 4060 ++ -- 4064 4056 4 bytes
From the above table we can observe that on increase of pointer variable for integers the address is
increased by two 4046 is original address and on increase its value will be 4048 because integer requires two
bytes.
Similarly characters, float numbers and long integers requires 1, 4 and 4 bytes respectively.
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int n; int n;
int *ptr; // pointer to an integer int *ptr; // pointer to an integer
ptr = &n; ptr = &n;
printf("Pointer ptr before Increment: %d \n", ptr); printf("Pointer ptr before Increment: %d \n", ptr);
ptr++; // Increment of ptr++ ptr--; // Decrement of ptr--
printf("Pointer ptr after Increment: %d \n", ptr); printf("Pointer ptr after Increment: %d \n", ptr);
return 0; return 0;
} }
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 4
2. Addition of integer to a pointer 3. Subtraction of integer to a pointer
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int n; int n;
int *ptr; // pointer to an integer int *ptr; // pointer to an integer
ptr = &n; ptr = &n;
printf("Pointer ptr before Addition: %d \n", ptr); printf("Pointer ptr before Subtraction: %d \n", ptr);
ptr = ptr + 3; // addition of 3 to ptr ptr = ptr - 3; // Subtraction of 3 to ptr
printf("Pointer ptr after Addition: %d \n", ptr); printf("Pointer ptr after Subtraction: %d \n", ptr);
return 0; return 0;
} }
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 5
Array manipulation using pointers: .
Pointer array is a homogeneous collection of indexed pointer variables that are references to a memory
location. It is generally used in C Programming when we want to point at multiple memory locations of a
similar data type in our C program. We can access the data by dereferencing the pointer pointing to it.
Syntax:
pointer_type *array_name [array_size];
Note: It is important to keep in mind the operator precedence and associativity in the array of pointers
declarations of different type as a single change will mean the whole different thing.
For example, enclosing *array_name in the parenthesis will mean that array_name is a pointer to an array.
#include <stdio.h>
int main()
{
return 0;
}
Output:
Value of var1: 10 Address: 6684360
Value of var2: 20 Address: 6684356
Value of var3: 30 Address: 6684352
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 6
USER-DEFINED DATA TYPES - Structures and Unions:
STRUCTURES [ BASICS OF STRUCTURES ]
Definition of Structure:
A Structure is a collection of one or more variables of different data types, grouped together under a
single name. (or)
A Structure is a collection of data items of different data types under a single name.
Features of Structures:
• Structures are used to hold related data belonging to different data types.
• Nesting of Structures is possible.
• It is also possible to pass Structure elements to a function.
• It is also possible to create Structure pointers.
Declaration of Structure:
Structure can be declared as given below,
Syntax:
struct <structure-name>
{
data_type member-1;
data_type member-2;
--- --- ---
data_type member-n;
};
struct <structure-name> variable-1, variable-2, … … , variable-n;
• Structure declaration always starts with struct keyword. Here, structure-name is known as tag.
• The struct declaration is enclosed with in a, pair of curly braces.
• Each member of structure may belong to different types of data.
• The individual members can be ordinary variables, arrays, pointers or other structures.
E.g. :
struct account struct account
{ {
int ac_no; int ac_no;
char ac_type; char ac_type;
(or)
char name[25]; char name[25];
float balance; float balance;
}; } oldcustomer, newcustomer;
struct account oldcustomer, newcustomer;
Syntax:
STRUCTURE_Variable = { value_1, value_2, ... , value_n };
Note: Individual structure members cannot be initialized within the template. Initialization is possible only
with the declaration of structure members.
Example:
struct student // student is called as structure “tag”
{
int rollno; // rollno & attendance are called as structure “members”
int attendance;
} s1={ 3001, 98 }; // s1 is called as structure “variable”
The above example assigns 3001 to the rollno and 98 to the attendance. Structure variable can be
initialized outside the function also.
Example:
struct student
{
int rollno;
int attendance;
};
struct student s1={ 3001, 98 };
struct student s2={ 3002, 97 };
Syntax
STRUCTURE_Variable . STRUCTURE_Member
E.g.
b1.author where, b1 - is a structure variable and
author - is a structure member
The different ways for storing values into structure variable is given below:
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 8
Example 1:
#include<stdio.h>
struct book
{
int bookid;
char bookname[30];
char author[25];
float price;
int year;
int pages;
char publisher[25];
};
int main()
{
struct book b1;
printf("Enter the Book Id: ");
scanf("%d", &b1.bookid);
printf("Enter the Book Name: ");
scanf("%s", b1.bookname);
printf("Enter the Author Name: ");
scanf("%s", b1.author);
printf("Enter the Price: ");
scanf("%f", &b1.price);
printf("Enter the Year: ");
scanf("%d", &b1.year);
printf("Enter the Total No. of Pages: ");
scanf("%d", &b1.pages);
printf("Enter the Publisher Name: ");
scanf("%s", b1.publisher);
Output:
Enter the Book Id: 1002
Enter the Book Name: C_Programming
Enter the Author Name: John_Doe
Enter the Price: 123.50
Enter the Year: 2015
Enter the Total No. of Pages: 649
Enter the Publisher Name: Tata_McGraw
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 9
Arrays of Structures:
An array of structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store information
about multiple entities of different data types. The array of structures is also known as the collection of
structures.
Example 2: C program to define an array of structures that stores information of 5 students and prints it.
#include<stdio.h>
struct student
{
int rollno;
char name[25];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0; i<5; i++)
{
printf("\nEnter Rollno: ");
scanf("%d", &st[i].rollno);
printf("\nEnter Name: ");
scanf("%s", st[i].name);
}
printf("\nStudents Information List:");
for(i=0; i<5; i++)
{
printf("\nRollno: %d, Name: %s", st[i].rollno, st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students Enter Rollno: 4 Student Information List:
Enter Rollno: 1 Enter Name: v yamini Rollno: 1, Name: k nithyasree
Enter Name: k nithyasree Enter Rollno: 5 Rollno: 2, Name: V Murali
Enter Rollno: 2 Enter Name: v poojitha Rollno: 3, Name: c v jagadeesh
Enter Name: V Murali Rollno: 4, Name: v yamini
Enter Rollno: 3 Rollno: 5, Name: v poojitha
Enter Name: c v Jagadeesh
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 10
Structures within structures: (or) [ Nested Structures ]
Definition:
Structure can be defined inside another structure. i.e., Structures can also be nested. (or)
Nested structure in C is a structure within structure. One structure can be declared inside another
structure in the same way structure members are declared inside a structure. (or)
Nested structure in C is a structure that contains one or more members that are themselves structures.
Declaration in 2 ways:
1) By separate nested structure: 2) By embedded nested structure:
#include<stdio.h> #include<stdio.h>
struct date struct account
{ {
int day; int acc_no;
int month; char acc_type;
int year; char name[25];
}; float balance;
struct account struct // Here, date tag – may / mayn’t present
{ { // called as Empty tag.
int acc_no; int day;
char acc_type; int month;
char name[25]; int year;
float balance; } lastpayment;
struct date lastpayment; };
};
struct account cust1; int main()
{
int main() struct account cust1 = { 101, ‘S’, "Samba",
{ 5310.25, { 31, 03, 2023 } };
struct account cust1 = { 101, ‘S’, "Samba", printf("Entered account Details are: ");
5310.25, { 31, 03, 2023 } }; printf("%d %c %s %6.2f %d-%d-%d", cust1.acc_no,
printf("Entered account Details are: "); cust1.acc_type, cust1.name, cust1.balance,
printf("%d %c %s %6.2f %d-%d-%d", cust1.acc_no, cust1.lastpayment);
cust1.acc_type, cust1.name, cust1.balance, return(0);
cust1.lastpayment); }
return(0);
}
Output: Output:
Note : printf() can also be written as, Note : Empty structure tag name is permissible only in
embedded nested structure.
printf("%d %c %s %6.2f %d-%d-%d", cust1.acc_no,
cust1.acc_type, cust1.name, cust1.balance,
cust1.lastpayment.day, cust1.lastpayment.month,
cust1.lastpayment.year);
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 11
UNIONS [ BASICS OF UNIONS ]
The concept of Union is borrowed from structure and the format are same as structure. The difference
between them is in terms of total memory space required to access its members.
Definition of Union:
"Union" is a composite data type that allows you to store different types of data in the same memory
location. Unlike structures, where each member has its own memory space, members of a union share the
same memory location. The size of a union is determined by the size of its largest member.
Declaration of Union:
Union can be declared as given below,
Syntax:
union <union-name>
{
data_type member-1;
data_type member-2;
--- --- ---
data_type member-n;
};
union <union-name> variable-1, variable-2, … … , variable-n;
• Union declaration always starts with uinon keyword. Here, union-name is known as tag.
• The union declaration is enclosed with in a, pair of curly braces.
• Each member of union may belong to different types of data.
• The individual members can be ordinary variables, arrays, pointers or other unions.
E.g. :
union account union account
{ {
int ac_no; int ac_no;
char ac_type; char ac_type;
(or)
char name[25]; char name[25];
float balance; float balance;
}; } oldcustomer, newcustomer;
union account oldcustomer, newcustomer;
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 12
Union Initialization:
Syntax:
UNION_Variable = { value_1, value_2, ... , value_n };
Note: Individual union members cannot be initialized within the template. Initialization is possible only with
the declaration of union members.
Example:
union student // student is called as union “tag”
{
int rollno; // rollno & attendance are called as union “members”
int attendance;
} s1={ 3001, 98 }; // s1 is called as union “variable”
The above example assigns 3001 to the rollno and 98 to the attendance. Union variable can be
initialized outside the function also.
Example:
union student
{
int rollno;
int attendance;
};
union student s1={ 3001, 98 };
union student s2={ 3002, 97 };
Syntax
UNION_Variable . UNION_Member
(or)
E.g.
ptr -> rollno = 14; where, ptr - is a pointer to specify the union
rollno - is a union member
The different ways for storing values into union variable is given below:
#include <stdio.h>
union MyUnion
{
int integer;
float floatingPoint;
char character;
};
int main()
{
union MyUnion data;
printf("Enter an integer: ");
scanf("%d", &data.integer);
printf("You entered: %d\n", data.integer);
Note : If we attempt to print all the outputs together, we cannot print the correct outputs. Means, members of
a union share the same memory location. The size of a union is determined by the size of its largest member.
The values of integer and floatingPoint members of union got corrupted because the final value
assigned to the variable has occupied the memory location and this is the reason that the value of character member
is getting printed very well.
#include <stdio.h>
union MyUnion
{
int integer;
float floatingPoint;
char character;
};
int main()
{
union MyUnion data;
printf("Enter an integer: ");
scanf("%d", &data.integer); Output:
printf("Enter a floating-point number: "); Enter an integer: 101
scanf("%f", &data.floatingPoint); Enter a floating-point number: 125.75
printf("Enter a character: "); Enter a character: c
scanf(" %c", &data.character); You entered: 1123778659
You entered: 125.75
printf("You entered: %.2f\n", data.floatingPoint); You entered: c
printf("You entered: %d\n", data.integer);
printf("You entered: %c\n", data.character);
Note: This union program approach produces a
return 0; wrong output.
}
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 14
Example 2: Union program using indirect membership operator ( -> ) / arrow operator `
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union employee
{
int empid;
char name[25];
char depart[15];
float salary;
};
union employee *emp = NULL;
int main()
{
emp = (union employee *) malloc( sizeof(union employee) );
printf("Employee Details: \n");
emp->empid = 101;
printf("Employee ID: %d\n", emp->empid);
strcpy(emp->name, "John Doe");
printf("Name: %s\n", emp->name);
strcpy(emp->depart, "Engineering");
printf("Department: %s\n", emp->depart);
emp->salary = 65000.00;
printf("Salary: %.2f\n", emp->salary);
free(emp); // Release dynamically allocated memory
return 0;
}
Output:
Employee Details:
Employee ID: 101
Name: John Doe
Department: Engineering
Salary: 65000.00
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 15
Difference between Structure and Union in C:
Structure Union
1. It is declared using the struct keyword. It is declared using the union keyword.
7. For above structure, memory allocation will be, For above union, the memory allocation will be based
int id - 02 Bytes on the size of the largest member because all
char name[25] - 25 Bytes members share the same memory space in a union.
float avg - 04 Bytes the largest member is the char name[25] array, which
Total memory allocation = 31 Bytes requires 25 Bytes (1 bytes x 25 = 25).
( 02 + 25 + 04 = 31 Bytes must require to access) Total memory allocation = 25 Bytes are enough.
(or)
The main differences between unions and structures can be summarized as follows:
Memory Allocation: Unions have members that share the same memory space, while structures have
separate memory space for each member.
Size: Unions have a size determined by the largest member, while structures have a size
determined by the sum of all members’ sizes.
Member Access: Only one member can be accessed at a time in a union, while structure members can be
accessed individually using the dot operator.
Initialization: Only the first member of a union can be explicitly initialized, whereas all members of
a structure can be initialized individually or collectively.
[Source: PROBLEM SOLVING AND PROGRAMMING (AK19) by Mr. V.SAMBASIVA, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE]
Introduction to Programming (AK23), Mr. P.Bhanu Praksh, M.Tech., (Ph.D), Asst. Professor, Dept. of CSE pg. 16