0% found this document useful (0 votes)
5 views

Pointers_Basics

The document provides an extensive overview of pointers in programming, particularly in the C language, detailing their definition, uses, and operations. It explains how pointers can access variables, manage memory, and facilitate complex data structures like arrays and linked lists. Additionally, it covers pointer arithmetic, initialization, and the relationship between pointers and arrays, as well as their application in structures and functions.

Uploaded by

akul.kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Pointers_Basics

The document provides an extensive overview of pointers in programming, particularly in the C language, detailing their definition, uses, and operations. It explains how pointers can access variables, manage memory, and facilitate complex data structures like arrays and linked lists. Additionally, it covers pointer arithmetic, initialization, and the relationship between pointers and arrays, as well as their application in structures and functions.

Uploaded by

akul.kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Pointers

Apr 6, 2025 Dept of I&CT 1 / 37


Pointer - Introduction

• Pointer is a memory location or a variable which


stores the memory address of another variable

• Pointers are much more commonly used in C than


in many other languages (such as BASIC, Pascal,
and certainly Java, which has no pointers).

Apr 6, 2025 Dept of I&CT 2 / 37


Common Uses of Pointers
• Accessing array elements.
• Passing arrays and strings to functions
• Passing arguments to a function when the function
needs to modify the original argument.
.
• Obtaining memory from the system.
• Creating data structures such as linked lists

Apr 6, 2025 Dept of I&CT 3 / 37


Why Pointers?
• It enables the access to a variable that is defined
outside the function
• Pointers reduce the length and complexity of a
program.
• They increase the execution speed
• The use of a pointer array to strings results in saving of
data storage space in the memory

Apr 6, 2025 Dept of I&CT 4 / 37


Concept

int Quantity =
50;
• This statement instructs the system to find a location for the
integer variable Quantity and puts the value 50 in that location.
• Assume that system has chosen address location 5000 for Quantity

Apr 6, 2025 Dept of I&CT 5 / 37


Concept
• During execution of the program, the system always associates
the name Quantity with the address 5000.
• We may have access to the value 50 by using either the name
of the variable Quantity or the address 5000.
• Since memory addresses are simply numbers, they can be
assigned to some variables which can be stored in memory,
like any other variable.
• To assign the address 5000 (the location of Quantity) to a
variable p, we can write:
p = &Quantity;
Such variables that hold memory addresses are called Pointer
Variables
Apr 6, 2025 Dept of I&CT 6 / 37
Concept

The operator & can be called address of and can be


used only with a simple variable or an array element.

Apr 6, 2025 Dept of I&CT 7 / 37


Valid and Invalid cases

• Invalid Cases:
 &50 (pointing at constant)
 int x[10];
&x (pointing at array name)
 &(x + y) (pointing at expressions).
• If x is an array, then expressions such as &x[0] and
&x[i+3] are valid and represent the addresses of 0th
and (i+3)th elements of x.

Apr 6, 2025 Dept of I&CT 8 / 37


Declaring and Initializing Pointers
• Declaration Syntax:
<datatype> *pt_name;
• This tells the compiler 3 things about the pt_name:
 The asterisk(*) tells the variable pt_name is a pointer
variable.
 pt_name needs a memory location.
 pt_name points to a variable of type datatype
• Example:
int *p; //declares a variable p as a pointer variable that points
to an integer data type.
• float *x; // declares x as a pointer to floating point variable.
Apr 6, 2025 Dept of I&CT 9 / 37
Declaring and Initializing Pointers
• Once a pointer variable has been declared, it can be
made to point to a variable using an assignment
statement:
int quantity;
p = & quantity;
• p now contains the address of quantity. This is known
as pointer initialization.

Apr 6, 2025 Dept of I&CT 10 / 37


To be taken care..
• Before a pointer is initialized, it should not be used.
• We must ensure that the pointer variables always point to the
corresponding type of data.
• Assigning an absolute address to a pointer variable is
prohibited. i.e. p = 5000
Note: A pointer variable can be initialized in its declaration
itself.
• Example: int x, *p = &x; declares x as an integer and then
initializes p to the address of x.
• int *p = &x, x; not valid
Apr 6, 2025 Dept of I&CT 11 / 37
Accessing a variable through its pointer
• When the operator * is placed before a pointer variable in an
expression on the R.H.S of equal sign, the pointer returns the value
of the variable quantity
• The * can be remembered as value at address. (*p where p is the
address!)
• Example:
p =&quantity;
n =*p; is equivalent to
n =*&quantity; which in turn equal to
n = quantity;
• & is the ’reference’ operator and can be read as ”address of”
• * is the ’dereference’ operator and can be read as ”value pointed
by”
Apr 6, 2025 Dept of I&CT 12 / 37
Understanding Pointers
void main ()
{
int firstvalue = 5, secondvalue = 15;
int ∗ p1, ∗ p2;
p1 = &firstvalue; / / p1 = address of firstvalue
p2 = &secondvalue; / / p2 = address of secondvalue
∗p1 = 10; / / value pointed by p1 = 10
∗p2 = ∗p1; / / value pointed by p2 = value pointed by
p1
p1 = p2; / / p1 = p2 (value of pointer is copied)
∗p1 = 20; / / value pointed by p1 = 20
Printf(”firstvalue is %d\n”,firstvalue);
Printf( ”secondvalue is %d\n”,secondvalue);
}Apr 6, 2025 Dept of I&CT 13 / 37
Operations on Pointers
• Pointer variables can be used in expressions. For example, if p1 and
p2 are properly declared and initialized pointers, then following are
valid:
 y = *p1* *p2 ; same as (*p1) * (*p2)
 sum = sum + *p1;
 z = 5 * - *p2 / *p1; same as ( 5 * (- (*p2)))/(*p1)
There is a blank space between / and *; otherwise treated
as comment.
 *p2 =*p2 +10;
 Addition of integers: p1 + 2 //address increments by 4
bytes
 Subtraction of integers from pointers: p2 - 2 //address
decrements by 4 bytes
Apr 6, 2025 Dept of I&CT 14 / 37
Operations on Pointers
• Subtraction of one pointer from another: p1 - p2 //difference
between two addresses
• Short hand operators may also be used with the pointers.
p1++;
- -p2;
Sum+=*p2;
• Pointers can also be used to compare things using relational
operators.
p1>p2;
p1==p2
p1!=p2;

Apr 6, 2025 Dept of I&CT 15 / 37


Operations on Pointers
• Invalid statements:
 Pointers are not used in division and multiplication.
p1/*p2;
p1*p2;
p1/3; not
allowed!
 Two pointers can
not be added.
p1 + p2 is
illegal.

Apr 6, 2025 Dept of I&CT 16 / 37


Scale Factor
• A scale factor is an increment or decrement given to a pointer
to memory address which changes the address of the pointer
to next memory address.
• When we increment a pointer, its value is increased by the
length of the data type that it points to. This length is
called the scale factor.
• For example,
p1++; where p1 is a pointer pointing to some integer
variable with an initial value, say 2800, then after p1 = p1
+ 1, the value of p1 will be 2802.
• We refer to this addition as pointer arithmetic.

Apr 6, 2025 Dept of I&CT 17 / 37


Pointers and Arrays
• When an 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.
• An array x is declared as follows and assume the base address of x is
1000.
int x[5] ={ 1, 2, 3, 4, 5};
• Array x, is a constant pointer, pointing to the first element x[0].
Value of x is 1000 (Base Address), the location of x[0] i.e., is x =
&x[0] = 1000.

Apr 6, 2025 Dept of I&CT 18 / 37


Pointers and Arrays
• An integer pointer variable p, can be made to point to an a
follows:
int x[5] = { 1, 2, 3, 4, 5};
int *p;
p = x; OR p = &x[0];
• p = &x; //Invalid
• Successive array elements can be accessed by writing:
printf(“%d”,*p);
p+ + ;
or
printf(“%d”, *(p+i));
i++;
Apr 6, 2025 Dept of I&CT 19 / 37
Pointers and Arrays
• Address of an element of x is given by:
Address of x[i] = base address + i * scale factor of (int)
Address of x[3]= 1000 + (3*2) = 1006
• The relationship between p and x is shown below.
p = &x[0] (=1000)
p + 1 = &x[1] (=1002)
p + 2 = &x[2]
(=1004) p + 3 =
&x[3] (=1006)
p + 4 = &x[4]
• *(p+3) is equivalent
to x[3].
Apr 6, 2025 Dept of I&CT 20 / 37
Example
#include <stdio.h>
void main( )
{
int arr[5] = { 31, 54, 77, 52, 93 };
for(int j=0; j<5; j++) //for each element,
printf(“%d”,∗(arr+j)); //print value
}
”arr” itself is a constant pointer which can be used to access
the elements.

Apr 6, 2025 Dept of I&CT 21 / 37


Example
/ / array accessed with pointer
#include <stdio.h>
void main()
{
int arr[] = { 31, 54, 77, 52, 93 }; //array
int ∗ptr; //pointer to arr
ptr = arr; //points to arr
for(int j=0; j<5; j++) //for each element,
Printf(“%d”,∗ptr++); //print value
}
”ptr” is a pointer which can be used to access the elements.

Apr 6, 2025 Dept of I&CT 22 / 37


Problems
• Write a program using pointers to exchange two
values (values stored in variables x &y).
• Write a program using pointers to find the sum of all
elements stored in an integer array.

Apr 6, 2025 Dept of I&CT 23 / 37


Pointers and Character Strings
• The statement char *cptr = name; declares cptr as a pointer to
a character and assigns address of the first character of name
as the initial value.
• The statement while(*cptr != ‘\0’) is true until the end of the
string is reached.
• When the while loop is terminated, the pointer cptr holds the
address of the null character (‘\0’)
• The statement length = cptr – name; gives the length of the
string name.
• A constant character string always represents a pointer to that
string.
• The following statements are valid: char *name; name =
“Delhi”;
Apr 6, 2025 Dept of I&CT 24 / 37
Pointers and 2D Array
int a[][2]={ {12, 22},
{33, 44} };
int (∗p)[2];
p=a; / / initialization

• Element in 2d represented as
*(*(a+ i )+j) or
* (* ( p + i )+ j)

Apr 6, 2025 Dept of I&CT 25 / 37


Pointers and 2D Array

Apr 6, 2025 Dept of I&CT 26 / 37


Pointers and 2D Array
#include <stdio.h>
void main()
{
int i, j, (∗p)[2], a[][2]={{12, 22}, {33, 44} };
p=a;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(“%d”, ∗(∗(p+i)+j));
}
}

Apr 6, 2025 Dept of I&CT 27 / 37


Array of Pointers
• We can use pointers to handle a table of strings.
char name[3][25];
name is a table containing 3 names, each with a maximum
length of 25 characters (including ’\0’)
• Total storage requirement for name is 75 bytes. But rarely all
the individual strings will be equal in lengths.
• We can use a pointer to a string of varying length as
char *name[3] = {”New Zealand”, ”Australia”, ”India” };

Apr 6, 2025 Dept of I&CT 28 / 37


Array of Pointers
• Declares name to be an array of 3 pointers to characters, each
pointer pointing to a particular name.
name[0]→ New Zealand
name[1]→Australia
name[2]→India
This declaration
allocates 28 bytes. -
Ragged Array
• The following statement
would print out all the 3
names.
for(i=0; i<=2;i++)
printf(“%s”,name[i
Apr 6, 2025 Dept of I&CT 29 / 37
]); or ∗(name + i);
Pointers and Structures

struct inventory
{
char name[30];
int number; float price;
}product[2], ∗ptr;

• ptr=product;
• Its members are accessed
using the following
notation
ptr→name
ptr→number
ptr→price
Apr 6, 2025 Dept of I&CT 30 / 37
Pointers and Structures
• The symbol → is called arrow operator (also known as member
selection operator)
• The data members can also be accessed using
• (*ptr).number
• Parentheses is required because ’.’ has higher precedence than the
operator *

Apr 6, 2025 Dept of I&CT 31 / 37


Function Returning Pointers
int ∗larger (int ∗, int ∗);
void main()
{
int a=10, b=20, ∗p;
p=larger (&a, &b);
printf(“%d”,∗p);
}
int ∗larger (int ∗x,
int ∗y)
{
if (∗x > ∗y)
return(x)
; else
return(
Apr 6, 2025 Dept of I&CT 32 / 37
y);
Dynamic Memory Allocation
• Dynamic memory allocation and deallocation is done using two functions:
malloc() and free().
• Memory allocation
ptr variable =(data type)malloc(sizeof(data type);

• Memory de-allocation
free(pointer variable)
Explain with structures

Apr 6, 2025 Dept of I&CT 33 / 37


Dangling reference:
Ex: int main(){
int *p;
{
int x=10;
p=&x;
printf(“%d”, x);
free(&x);
}
printf(“%d”, *p);- dangling reference
}
Solution: Initialise pointer to NULL
Apr 6, 2025 Dept of I&CT 34 / 37

You might also like