unit-1
unit-1
Pointers
Course Instructor
Dr. Nagarathna N
Department of CSE(ICB), BMSCE
Introduction to Pointers
⚫ Every variable in C has a name and a value associated with it. When a variable is
declared, a specific block of memory within the computer is allocated to hold the
value of that variable. The size of the allocated block depends on the type of the
data.
int x = 10;
⚫ When this statement executes, the compiler sets aside 2 bytes of memory to hold
the value 10. It also sets up a symbol table in which it adds the symbol x and the
relative address in memory where those 2 bytes were set aside.
⚫ Thus, every variable in C has a value and an also a memory location (commonly
known as address) associated with it. Some texts use the term rvalue and lvalue
for the value and the address of the variable respectively.
⚫ The rvalue appears on the right side of the assignment statement and cannot be
used on the left side of the assignment statement.
⚫ int x=10;
⚫ int *ptr;
⚫ ptr=&x;
Introduction to Pointers
⚫ A pointer is a variable that contains the memory
location of another variable.
⚫ Therefore, a pointer is a variable that represents the
location of a data item, such as a variable or an array
element.
⚫ A pointer variable can store only the address of a
variable.
⚫ Pointers are not allowed to store actual memory
addresses, but only the addresses of variables of a given
type.
⚫ Therefore, the statement
Introduction to Pointers
⚫ Applications of pointers :
are double */
⚫ char * start; /* start is a pointer to a char */
⚫ Indirection operator *
⚫ We can dereference a pointer i.e. refer to the value of the
variable to which it points, by using unary ‘*’ operator known as
the indirection operator.
int x, *p;
x=5;
p=&x;
*p = 10;
⚫ * is equivalent to writing value at address
Pointer Illustrations
#include <stdio.h>
int main()
{
int num, *pnum1,*pnum2;
pnum1=#
*pnum1=10;
pnum2=pnum1;
printf(“the value of num is %d \t %d \t %d \n”,num,
*pnum1,*pnum2);
printf(“the address of num is %x \t %x \t %x \n”,&num,
pnum1,pnum2);
return 0;
}
Output : ?
Pointer Illustrations
#include <stdio.h>
int main()
{
int num, *pnum1,*pnum2;
pnum1=#
*pnum1=10;
pnum2=pnum1;
printf(“the value of num is %d \t %d \t %d \n”,num,
*pnum1,*pnum2);
printf(“the address of num is %x \t %x \t %x \n”,&num,
pnum1,pnum2);
return 0;
}
Output :the value of num is 10 10 10
Pointer Illustrations
#include <stdio.h>
int main()
{
int a=3,b=5, *pnum;
float*pfnum;
pnum=&a;
printf(“the value of a is %d \n”, *pnum);
pnum=&b;
printf(“the value of b is %d \n”,*pnum);
pfnum= &a; //invalid
return 0;
}
Output :the value of a is 3
the value of b is 5
Pointer Illustrations
#include <stdio.h>
int main()
{
int num, *pnum;
pnum=#
*pnum=10;
printf(“the *pnum is %d \n”, *pnum);
printf(“the num is %d \n”,num);
*pnum= *pnum+1;
printf(“ After Increment the *pnum is %d \n”, *pnum);
printf(“After Increment the num is %d \n”,num);
return 0;
}
Output: the *pnum is 10
the num is 10
After Increment the *pnum is 11
After Increment the num is 11
Write a program to test whether a number is positive, negative, or equal to zero
#include <stdio.h>
int main()
{
int num, *pnum = #
printf("\n Enter any number: ");
scanf("%d", pnum);
if(*pnum>0)
printf("\n The number is positive");
else
{
if(*pnum<0)
printf("\n The number is negative");
else
printf("\n The number is equal to zero");
}
return 0;
}
Pointer Arithmetic
int main()
{
float num1,num2,sum=0.0, *nump1,*nump2, *sump;
nump1=&num1;
nump2=&num2;
sump=∑
scanf(“%f %f”,nump1,nump2);
*sump= *nump1+ *nump2;
printf(“the sum of %f \t %f \t is %f
\n”,*nump1,*nump2,*sump);
return 0;
}
Output : the sum of 2.5 3.4 is 5.9
⚫ #include <stdio.h>
⚫ int main()
⚫ {
⚫ char *ch = "Hello World";
⚫ printf("%s", ch);
⚫ return 0;
⚫ }
Passing arguments to functions using Pointers
⚫ Pointers provide a mechanism to modify data declared in one function
using code written in another function.
⚫ The calling function sends the address of the variables.
⚫ The called function receives them using Pointers.
Syntax to be followed
⚫ Formal Parameters are Pointers
⚫ Use dereferencing operator(*) to use these pointer variables
⚫ The actual arguments are address of the variables
WAP to add two integers using function
#include<stdio.h>
void sum(int*,int*,int *);
int main()
{
int n1,n2,total;
printf(“Enter the first number\n”);
scanf(“%d”,&n1);
printf(“Enter the second number\n”);
scanf(“%d”,&n2);
sum(&n1,&n2,&total);
printf(“Total is %d \n”, total); return 0;
}
void sum(int *a, int *b, int *s)
{ *s=*a+*b;
}
Regular functions without pointers
sum(1,2);
OR
sum(x,y);
void sum(int a, int b)
{
int s;
s=a+b;
printf(“%d”, s);
}
Arrays
⚫ int a[10];
⚫ int *x;
⚫ x=a;
⚫ x++ to access the elements in the array.
Call by Reference
⚫ Since arguments are not copied into a new variable better
time and space efficiency
⚫ The called function can change the value of the argument
and the change is reflected in the calling function
⚫ The reference can be used to return multiple values
Swapping two variables
void swap_call_by _val(int,int)
void swap_call_by _ref(int *,int *)
int main()
{
int a=1,b=2,c=3,d=4;
printf(“In main() a=%d,b=%d\n”,a,b);
swap_call_by_val(a,b);
printf(“In main() a=%d,b=%d\n”,a,b);
printf(“In main() c=%d,d=%d\n”,c,d);
swap_call_by_ref(&c,&d);
printf(“In main() c=%d,d=%d\n”,c,d);
return 0;
}
Swapping two variables
void swap_call_by _val(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf(“In function() a=%d,b=%d\n”,a,b);
}
void swap_call_by _ref(int *c,int *d)
{
int temp;
temp=*c;
*c=*d;
*d=temp;
printf(“In function() c=%d,d=%d\n”,*c,*d);
}
Generic Pointers
⚫ A generic pointer is a pointer variable that has void as its data type.
⚫ The void pointer, or the generic pointer, is a special type of pointer that
can point to variables of any data type.
⚫ It is declared like a normal pointer variable but using the void keyword as
the pointer’s data type.
void *ptr;
⚫ In C, since you cannot have a variable of type void, the void pointer will
therefore not point to any data and, thus, cannot be dereferenced.
⚫ You need to cast a void pointer to another kind of pointer before using it.
⚫ Generic pointers are often used when you want a pointer to point to data of
different types at different times
⚫ #include <stdio.h>
⚫ int main()
⚫ {
⚫ int x=10;
⚫ char ch = ‘A’;
⚫ void *gp;
⚫ gp = &x;
⚫ printf("\n Generic pointer points to the integer value = %d", *(int*)gp);
⚫ gp = &ch;
⚫ printf("\n Generic pointer now points to the character= %c", *(char*)gp);
⚫ return 0;
⚫ }
⚫ Output
⚫ Generic pointer points to the integer value = 10
⚫ Generic pointer now points to the character = A
Pointer to Pointers
⚫ you can also use pointers that point to pointers. The pointers in turn point to data or even to
other pointers. To declare pointers to pointers, just add an asterisk * for each level of
reference.
⚫ For example, consider the following code:
int x=10;
int *px, **ppx;
px = &x;
ppx = &px;
⚫ Let us assume, the memory locations of these variables are as shown in figure.
⚫ Now if we write,
printf("\n %d", **ppx);
⚫ Then, it would print ?,the value of x
Drawbacks of Pointers
⚫ Although pointers are very useful in C, they are not free from limitations. If used
incorrectly, pointers can lead to bugs that are difficult to unearth.
⚫ For example, if you use a pointer to read a memory location but that pointer is
pointing to an incorrect location, then you may end up reading a wrong value. An
erroneous input always leads to an erroneous output. Thus however efficient your
program code may be, the output will always be disastrous. Same is the case when
writing a value to a particular memory location
⚫ #include <stdio.h>
int main() {
int x, *px;
x=10;
px=&x;
*px = 20;
printf("\n %d", *px);
return 0;
}
Drawbacks of Pointers
int x, *px;
x=10;
px = x;
⚫ Error: It should be px = &x;
Drawbacks of Pointers
Since the size of int is 4 bytes, this statement will allocate 20 bytes of memory.
And, the pointer ptr holds the address of the first byte in the allocated memory.
Calloc()
1.“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks
of memory of the specified type. it is very much similar to malloc() but has two different points and these are:
2.It initializes each block with a default value ‘0’.
3.It has two parameters or arguments as compare to malloc().
Like any other data type, memory is allocated for the structure
when we declare a variable of the structure.
For example, we can define a variable of student by writing:
struct student stud1;
Here, struct student is a data type and stud1 is a variable.
Look at another way of declaring variables. In the following syntax, the
variables are declared at the time of structure declaration.
struct student { int r_no;
char name[20];
char course[20];
float fees; } stud1, stud2;
Structures Declaration
⚫ Look at another way of declaring variables. In the following syntax, the
variables are declared at the time of structure declaration.
struct student { int r_no;
char name[20];
char course[20];
float fees; } stud1, stud2;
⚫ In this declaration we declare two variables stud1 and stud2 of the structure
student. So if you want to declare more than one variable of the structure,
then separate the variables using a comma.
⚫ When we declare variables of the structure, separate memory is
allocated for each variable.
⚫ NOTE: care should be taken to ensure that the name of structure and the
name of a structure member should not be the same. Moreover, structure
name and its variable name should also be different.
Structures Declaration - typedef
⚫ When we precede a struct name with the typedef keyword, then the struct
becomes a new type.
typedef struct student { int r_no;
char name[20];
char course[20];
float fees; };
⚫ Now that you have preceded the structure’s name with the typedef
keyword, student becomes a new data type.
⚫ Therefore, now you can straightaway declare the variables of this new data
type as you declare the variables of type int, float, char, double, etc.
⚫ To declare a variable of structure student, you may write
student stud1;
⚫ Note that we have not written struct student stud1.
Initialization of Structures
⚫ The general syntax to initialize a structure variable is as follows:
struct struct_name { data_type member_name1;
data_type member_name2;
data_type member_name3;
.....................}struct_var = {const1, const2, const3,...};
OR
struct struct_name { data_type member_name1;
data_type member_name2;
data_type member_name3;
....................... };
struct struct_name struct_var = {constant1, constant2, constant 3,...};
Initialization of Structures
struct student { int r_no;
char name[20];
char course[20];
float fees; }stud1 = {01, "Rahul", "BCA", 45000};
Or, by writing,
struct student stud1 = {01, "Rahul", "BCA", 45000};
Accessing the Members of a Structure
⚫ A structure member variable is generally accessed using a '.' (dot) operator.
⚫ The syntax of accessing a structure or a member of a structure can be given as:
struct_var.member_name
⚫ The dot operator is used to select a particular member of the structure.
⚫ For example, to assign values to the individual data members of the structure variable
studl:
stud1.r_no = 01; stud1.name = "Rahul"; stud1.course = "BCA"; stud1.fees = 45000;
⚫ To input values for data members of the structure variable stud1, we may write
scanf("%d", &stud1.r_no);
scanf("%s", stud1.name);
⚫ Similarly, to print the values of structure variable stud1, we may write
printf("%s", stud1.course);
printf("%f", stud1.fees);
⚫ Of all the operators –>, . , ( ), and [] have the highest priority. This is evident from the
following statement
stud1.fees++ will be interpreted as (stud1.fees)++.
Problem
⚫ Write a program using structures to read and display the information about a
student.
#include <stdio.h>
#include <conio.h>
int main()
{
struct student
{
int roll_no;
char name[80];
float fees;
char DOB[80];
};
struct student stud1;
clrscr();
printf("\n Enter the roll number : ");
scanf("%d", &stud1.roll_no);
printf("\n Enter the name : ");
scanf("%s", stud1.name);
printf("\n Enter the fees : ");
scanf("%f", &stud1.fees);
printf("\n Enter the DOB : ");
scanf("%s", stud1.DOB);
printf("\n ********STUDENT'S DETAILS *******");
printf("\n ROLL No. = %d", stud1.roll_no);
printf("\n NAME = %s", stud1.name);
printf("\n FEES = %f", stud1.fees);
printf("\n DOB = %s", stud1.DOB);
getch();
return 0;
}
Output
Enter the roll number : 01
Enter the name : Rahul
Enter the fees : 45000
Enter the DOB : 25–09–1991
********STUDENT’S DETAILS *******
ROLL No. = 01
NAME = Rahul
FEES = 45000.00
DOB = 25–09–1991
Problem2
⚫ Write a program to read, display, add, and subtract two complex numbers.
⚫ #include <stdio.h>
⚫ #include <conio.h>
⚫ int main()
⚫ {
⚫ typedef struct complex
⚫ {
⚫ int real;
⚫ int imag;
⚫ }COMPLEX;
⚫ COMPLEX c1, c2, sum_c, sub_c;
NESTED STRUCTURES
typedef struct
{ char first_name[20];
char mid_name[20];
char last_name[20];
}NAME;
typedef struct
{ int dd;
int mm;
int yy;
}DATE;
typedef struct
{ int r_no;
NAME name;
char course[20];
DATE DOB;
float fees;
} student;
NESTED STRUCTURES
student stud1;
stud1.r_no = 01;
stud1.name.first_name = “Rema";
stud1.name.mid_name = "Raj";
stud1.name.last_name = "Thareja";
stud1.course = "BCA";
stud1.DOB.dd = 15;
stud1.DOB.mm = 09;
stud1.DOB.yy = 1990;
stud1.fees = 45000;
Problem3
⚫ Write a program to read and display the information of a student using a nested
structure.
ARRAYS OF STRUCTURES
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
};
struct struct_name struct_var[index];
Consider the given structure definition.
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
A student array can be declared by writing,
struct student stud[30];
ARRAYS OF STRUCTURES
To assign values to the ith student of the class, we will write
stud[i].r_no = 09;
stud[i].name = "RASHI";
Structures and Unions 147
stud[i].course = “BE";
stud[i].fees = 60000;
In order to initialize the array of structure variables at the time of declaration, we can
write as
follows:
struct student stud[3] = {{01, "Aman", "BCA", 45000},{02, "Aryan", "BCA",
60000},
{03, "John", "BCA", 45000}};
Problem4
⚫ Write a program to read and display the information of all the students in a class.
Then edit the details of the ith student and redisplay the entire information.
Basic Terminology
⚫ Our aim is to design good programs,
⚫ where a good program is defined as a program that
runs correctly
is easy to read and understand
is easy to debug and
is easy to modify
⚫ A program should undoubtedly give correct results, but along with that it should
also run
efficiently.
⚫ A program is said to be efficient when it executes in minimum time and with
minimum
memory space.
Basic Terminology
⚫ In order to write efficient programs we need to apply certain data management
concepts.
⚫ Data structure is a crucial part of data management.
⚫ A data structure is basically a group of data elements that are put together under
one name, and which defines a particular way of storing and organizing data in a
computer so that it can be used efficiently.