[go: up one dir, main page]

0% found this document useful (0 votes)
22 views48 pages

PPS Pointers

Uploaded by

Varshith Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views48 pages

PPS Pointers

Uploaded by

Varshith Reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

UNIT -III

POINTERS
Introduction to Pointers
Pointer Declaration and Initialization
Pointer Arithmetic and pointer Expressions
Pointers and Arrays
Pointers and Strings
Pointer to Structure
Call by Reference
Pointer to Pointer
Dynamic Memory Allocation
What is Pointer in C?
A pointer is a variable that stores the address of another variable.
This variable can be of type int, char, array, function, or any other
pointer. It is a derived data type in c.
For example, an integer variable holds (or you can say stores) an
integer value, however an integer pointer holds the address of a
integer variable.
However, in 32-bit architecture the size of a pointer is 2 byte.
Advantages:
• Pointers used to access the address of the variable.
• Pointers increase the execution speed of program.
• Pointers are an important concept in datastructures.
• Pointers are used for dynamic memory allocation.
• Pointers makes possible to return more than one value in
functions .
• Pointers make the programs simple and reduce their length.
Pointer Declarations:
Pointer declaration is similar to other type of variable except
asterisk (*) character before pointer variable name.
• Here is the syntax to declare a pointer
datatype *poitername;
Data type of a pointer must be same as the data type of the
variable to which the pointer variable is pointing.
Ex: int *ptr;
float *ptr;
char *ptr;
• ptr is the name of pointer variable (name of the memory
blocks in which address of another variable is going to be
stored).
• The data type int tells to the compiler that pointer ptr will
store memory address of integer type variable.
Initialization of C Pointer variable:
Pointer Initialization is the process of assigning address of a
variable to a pointer variable. It contains the address of a
variable of the same data type .In C language address
operator (&) is used to determine the address of a variable.
Ex: int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
• Pointer variable always points to variables of the same
datatype.
For example:
float a;
int *ptr = &a; // ERROR, type mismatch
Accessing address and value of variable using
pointer:
We can get the value of p(pointer variable) which is the address
of a (integer variable)

1) P will print the stored value (memory address of a)


2)*p will print the value which is stored at the memory addressin
the p (value of variable a)

Ex: pointer declaration, Initialization and accessing address,


value using pointer variable
Ex:#include <stdio.h>
int main()
{
int a=10; //variable declaration
int *p; //pointer variable declaration
p=&a ; //store address of variable a in pointer p
printf("Address stored in a variable p is:%x\n",p); //accessing the
address
printf("Value stored in a variable p is:%d\n",*p); //accessing the
value
return 0;
}
o/p: Address stored in a variable p is:62345678
Value stored in a variable p is:10
Pointer operators in c:
C provides two pointer operators, which are
1) Address of Operator( &)
2) Indirection Operator (*).
1) Address of Operator( &) :
 Returns the address of a variable
 The & is a unary operator that returns the memory address of
its operand(variable)
2) Indirection Operator (*):
The second operator is indirection Operator(*) It is a unary
operator that returns the value of the variable located at the
address specified by its operand.
 * is called as indirection (or) dereference (or) value at
address operator
void main()
{
int a=10;
int *p;
p=&a;
printf(“value of a is%d\n”,a);
printf(“value of a is %d\n”,*p);
printf(“Address of a is %u\n”,&a);
printf(“Address of a is %u\n”,p);
printf(“Address of a is %u\n”,&p);
}
In C, there are two equivalent ways to access and manipulate a
variable content
• Direct access: we use directly the variable name
• Indirect access: we use a pointer to the variable
Pointer Expressions:
C supports a rich set of built-in operations like arithmetic,
relational, assignment, conditional, etc. which can be
performed on identifiers. Just like any other variable, these
operations can be also performed on pointer variables.
Like other variables pointer variables can be used in
expressions.
If p1 and p2 are properly declared and initialized pointers, then
the following statements are valid:
Y=*p1 * *p2;
sum=sum+*p1;
*p2=*p2+10;
*p1=*p1+*p2;
Z=*p2/ *p1;
//program on pointer Expressions
void main()
{
int a=12,b=4,x,y,z;
int *p1,*p2;
p1=&a,p2=&b;
x=(*p1)*(*p2)-6;
y=*p1+*p2;
printf(“a=%d,b=%d\n”,a,b);
printf(“x=%d,y=%d\n”,x,y);
*p2=*p2+3;
*p1=*p2-5;
z=*p1**p2-6;
printf(“a=%d b=%d\n”,a,b);
printf(“z=%d\n”,z);
}
Pointer Arithmetic in C:
We can perform arithmetic operations on the pointers like
addition, subtraction, etc. However, as we know that pointer
contains the address, the result of an arithmetic operation
performed on the pointer will also be a pointer
Following arithmetic operations are possible on the pointer in C
language:
• Increment(++)
• Decrement(--)
• Adding/subtracting integer value to/from a pointer
1)Incrementing Pointer in C:
If we increment a pointer by 1, the pointer will start pointing to
the immediate next location. This is somewhat different from
the general arithmetic since the value of the pointer will get
increased by the size of the data type to which the pointer is
pointing.
For 32-bit int variable, it will be incremented by 2 bytes.
For 64-bit int variable, it will be incremented by 4 bytes.
• The Rule to increment the pointer is given below:
new_address= current_address + i * size_of(data type)
Where i is the number by which the pointer get increased.
Ex: Let's see the example of incrementing pointer variable on
64-bit architecture.
#include<stdio.h>
int main()
{
int number=50;
int *p; //pointer to int
p=&number;
printf("Address of p variable is %u \n",p);
p=p+1 (or) p++;
printf(after increment: address of p variable is
%u ”,p); //p will get incremented by 4 bytes.
return 0;
}
o/p: Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Decrementing Pointer in C:
Like increment, we can decrement a pointer variable. If
we decrement a pointer, it will start pointing to the
previous location.
16 bit Machine (Turbo C)
 In a 16 bit machine, size of all types of pointer,
be it int*, float*, char* or double* is always 2 bytes.
 which decreases its value by the number of bytes of its
data
type
• The formula of decrementing the pointer is given below:
new_address= current_address - i * size_of(data type)

Ex: Let's see the example of decrementing pointer variable


#include <stdio.h>
void main()
{
int number=50;
int *p; //pointer to int
p=&number;
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \
n",p);
}
o/p: Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
C Pointer Addition:
We can add a value to the pointer variable.
When a pointer is added with a value, the value is first multiplied by the
size of data type and then added to the pointer.
• The formula of adding value to pointer is given below:
new_address= current_address + (number * size_of(data type))

C Pointer Subtraction:
• Like pointer addition, we can subtract a value from the pointer
variable. Subtracting any number from a pointer will give an address.
The formula of subtracting value from the pointer variable is given
below:
new_address= current_address- (number * size_of(data type))
Let's see the example of adding value to pointer variable
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
}
o/p: Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
Let's see the example of subtracting value from the pointer
variable
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \
n",p);
}
o/p: Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
Illegal arithmetic with pointers:
• There are various operations which can not be performed
on pointers. Since, pointer stores address hence we must
ignore the operations which may lead to an illegal
address, for example, addition, and multiplication. A list of
such operations is given below.
• Address + Address = illegal
• Address * Address = illegal
• Address % Address = illegal
• Address / Address = illegal
• Address & Address = illegal
• Address ^ Address = illegal
• Address | Address = illegal
• ~Address = illegal
Pointer and Arrays in C:
When array is declared ,the compiler allocates a base address
and sufficient amount of storage to contain all the elements of
the array in contiguous memory locations
We declare an array x as follows
Ex: int arr[5] = { 1, 2, 3, 4, 5 };
Suppose the base address of arr is 1000 and each integer
requires two bytes, the five elements will be stored as follows:
Variable arr will give the base address, which is a constant
pointer pointing to arr[0]. Hence arr contains the address
of arr[0] i.e 1000.
arr has two purpose –
• It is the name of the array
• It acts as a pointer pointing towards the first element in the
array.
arr is equal to &arr[0] by default
Creating a pointer to array:
If we declare p as an integer pointer ,then we can make the
pointer p to print to the array x by the following assignment
p=x; (or) p=&x[0];
Now we can access every value of x using p++ to move from
one element to another.
The relationship between p and x is
P=&x[0]
P+1=&x[1]
p+2=&x[2]
P+3=&x[3]
P+4=&x[4]
Address of x[3]=baseaddress+(3*sizeof(int))
x[3]=1000+(3*2)=1006
*(p+3) gives the value of x[3]
(p+3) gives the address of &x[3]
Use a pointer to an array, and then use that pointer to access the
array elements. For example,
#include<stdio.h>
void main()
{
int x[5] = {1, 2, 3,4,5};
int *p ;
p=x (or) p=&x[0];
for (int i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
} o/p:1 2 3 4 5
C - Pointers and Strings:
We know that a string is a sequence of characters which we save in
an array. And in C programming language the \0 null character
marks the end of a string.
Creating a string:
In the following example we are creating a string using
character array of size 6.
char str[6] = "Hello";
The above string can be represented in memory as follows .
Creating a pointer for the string:
The variable name of the string str holds the address of the first
element of the array i.e., it points at the starting memory
address.
So, we can create a character pointer ptr and store the address
of the string str variable in it. This way, ptr will point at the
string str.
In the following code we are assigning the address of the
string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.
Accessing string via pointer:
#include <stdio.h>
int main()
{
char str[6] = "Hello";
char *ptr = str;
while(*ptr != '\0')
{
printf("%c", *ptr); // move the ptr pointer to the next memory
location
ptr++;
}
return 0;
}
Pointer to Pointer (Double Pointer):
As we know that, a pointer is used to store the address of a
variable in C. Pointer reduces the access time of a variable.
However, In C, we can also define a pointer to store the
address of another pointer. Such pointer is known as a double
pointer (pointer to pointer). The first pointer is used to store
the address of a variable whereas the second pointer is used to
store the address of the first pointer.
How to declare a Pointer to Pointer :

Declaring Pointer to Pointer is similar to declaring pointer in C.


The difference is we have to place an additional ‘*’ before the
name of pointer.
The syntax of declaring a double pointer is given below.
int **p; // declaring double pointers
Here p is a double pointer. There must be two *’s in the
declaration of double pointer.

The first pointer ptr1 stores the address of the variable and the
second pointer ptr2 stores the address of the first pointer.
#include <stdio.h>
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Pointer to Structure
A structure pointer is defined as the pointer which points to the address of the memory block that stores a structure
known as the structure pointer. Complex data structures like Linked lists, trees, graphs, etc. are created with the help of
structure pointers. The structure pointer tells the address of a structure in memory by pointing the variable to the
structure variable.
Example:

// C program to demonstrate structure pointer


#include <stdio.h>

struct point {
int value;
};

int main()
{

struct point s;

// Initialization of the structure pointer


struct point *ptr = &s;

return 0;
}
Pointer to Structure
Accessing the Structure Member with the Help of Pointers
There are two ways to access the members of the structure with the help of a structure pointer:

With the help of (*) asterisk or indirection operator and (.) dot operator.
With the help of ( -> ) Arrow operator.
Below is the program to access the structure members using the structure pointer with the help of the dot operator.
// C Program to demonstrate Structure pointer
#include <stdio.h>
#include <string.h>

struct Student
{
int roll_no;
char name[30];
char branch[40];
int batch;
};

int main()
{

struct Student s1;


struct Student* ptr = &s1;

s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;

printf("Roll Number: %d\n", (*ptr).roll_no);


printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);

return 0;
}
O/P
Pointer to Structure
Below is the program to access the structure members using the structure pointer with the
help of the Arrow operator. In this program, we have created a Structure Student containing
structure variable s. The Structure Student has roll_no, name, branch, and batch.

Output:
// C Program to demonstrate Structure pointer
#include <stdio.h>

Enter the Roll Number of Student


#include <string.h>

// Creating Structure Student


struct Student { 27
int roll_no;
char name[30]; Enter Name of Student
char branch[40];
int batch; Kamlesh_Joshi
};
Enter Branch of Student
// variable of structure with pointer defined
struct Student s, *ptr; Computer_Science_And_Engineering
int main() Enter batch of Student
{
2019
ptr = &s;
// Taking inputs Student details are:
printf("Enter the Roll Number of Student\n");
scanf("%d", &ptr->roll_no); Roll No: 27
printf("Enter Name of Student\n");
scanf("%s", &ptr->name); Name: Kamlesh_Joshi
printf("Enter Branch of Student\n");
scanf("%s", &ptr->branch); Branch: Computer_Science_And_Engineering
printf("Enter batch of Student\n");
scanf("%d", &ptr->batch); Batch: 2019
// Displaying details of the student
printf("\nStudent details are: \n");

printf("Roll No: %d\n", ptr->roll_no);


printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
printf("Batch: %d\n", ptr->batch);

return 0;
}
Self Referential Structure
A self-referential structure is a structure that can have members which point to a structure variable of the same type.
They can have one or more pointers pointing to the same type of structure as their member. The self-referential structure
is widely used in dynamic data structures such as trees, linked lists, and so on. The next node of a node will be pointed in
linked lists, which consists of the same struct type. It is a unique type of structure containing a member of its type. The
member of its type is a pointer variable of the same structure in which it has been declared. In the context of blockchain,
each block is linked to a previous node or a next node, similar to a linked list.
Syntax:

struct structure_name
{
datatype datatype_name;
structure_name * pointer_name;
}
E.g.:
struct node
{
int data;
struct node *next;
};
Where ‘next’ is a pointer to a struct node variable, it should be remembered that the pointer to the structure is similar to
the pointer to any other variable. Hence, a self-referential data structure is generally a structure definition that includes
at least one member that is a pointer to the structure of its kind.
The self-referential structures are beneficial in many applications that involves linked data members, such as trees and
lists. Unlike a static data structure such as an array where the size of the array limits the number of elements that can be
inserted into the array, the self- referential structure can dynamically be contracted or expanded. Operations such as
insertion or deletion of nodes in a self-referential structure involve simple alteration of the pointers present within them.
Types of self-referential structures

Types of self-referential structures


Self-referential structure with a single link: these structures are allowed to have only one self-pointer as their member.
E.g.:

#include <stdio.h>
#include <conio.h>
struct ref
{
int data;
char val;
struct ref* link;
}
int main()
{
struct ref object1; //link1
object1.link = NULL;
object1.data = 10;
object1.val = 20;
struct ref object2; //
object2.link = NULL;
object2.data = 30;
object2.val = 40;
object1.link = &object2;
printf (“%d \n”, object1.link -> data);
printf (“%d \n”, object1.link -> val);
return 0;
}
Output:

30 40
Dynamic memory allocation in C:
The concept of dynamic memory allocation in c
language enables the C programmer to allocate memory at
runtime. Dynamic Memory Allocation can be defined as a
procedure in which the size of a data structure (like Array) is
changed during the runtime.
Dynamic memory allocation in c language is possible by 4
functions of stdlib.h header file.
• malloc()
• calloc()
• realloc()
• free()
These functions are defined in the <stdlib.h> header file.
1.malloc() function in C:
The name "malloc" stands for memory allocation.
The malloc() function allocates single block of requested memory.
The “malloc” or “memory allocation” method in C is used to
dynamically allocate a single large block of memory with the specified
size
It doesn’t Iniatialize memory at execution time so that it has initializes
each block with the default garbage value initially
It returns NULL if memory is not sufficient.
syntax: (type cast *) malloc(number*sizeof(datatype));
Ex: ptr= (int *) malloc( 10*sizeof(int));
The above statement allocates 40 bytes of memory. It's because the size
of int is 4 bytes. And, the pointer ptr holds the address of the first byte
in the allocated memory.
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
2.calloc() function in C:
The name "calloc" stands for contiguous allocation.
The calloc() function allocates multiple block of requested memory.
• it is very much similar to malloc() but has two different points and
these are:
• It initializes each block with a default value ‘0’.
• It has two parameters or arguments as compare to malloc().
• It returns NULL if memory is not sufficient.
Syntax:
ptr= (type cast *) calloc(number,sizeof(int));
here, n is the no. of elements and element-size is the size of each
element.
Ex: ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25
elements each with the size of the float.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
if(ptr==NULL)
{
printf("Sorry! unable to allocate memory");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
}
3.realloc() function in C:
If memory is not sufficient for malloc() or calloc(), you can
reallocate the memory by realloc() function
Syntax: (type cast *)realloc(pointer name,n*sizeof(int));
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL)
{
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
p = (int*) realloc(p, 6);
printf("\nEnter elements of array : ");
for(i = 0; i< n; ++i) {
scanf("%d", p + i);
s += *(p + i); }
printf("\nSum : %d", s); } In the above program, The memory block is allocated by calloc() and sum of
elements is calculated. After that, realloc() is resizing the memory block from 4 to 6 and calculating their
sum.
free() function:
The function free() is used to de-allocate the memory
allocated by the functions malloc ( ), calloc ( ),
free() Syntax:
free (pointer name);

You might also like