SlideShare uma empresa Scribd logo
1 de 34
Baixar para ler offline
Pointers
Md. Imran Hossain Showrov (showrovsworld@gmail.com)
18
1
Outline
 What is a Pointer?
 How to declare a pointer?
 Pointers and One-dimensional Arrays
 Difference Between Pointers and Arrays
 Dynamic Memory Allocation
 Several Declaration Involving Pointers
 Applications of Pointer
 Advantages of Pointer
What is a Pointer?
 Pointers are variables that contain memory addresses
as their values.
 A variable name directly references a value.
 A pointer indirectly references a value. Referencing a
value through a pointer is called indirection.
 A pointer variable must be declared before it can be
used.
What is a Pointer? (cont..)
 A pointer is a variable that represents the location
(rather than the value) of a data item, such as a
variable or an array element.
 Every variable is a memory location and every
memory location has its address defined which can
be accessed using ampersand (&) operator, which
denotes an address in memory.
Example 1
 A simple example to understand how to access the
address of a variable without pointers?
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
printf("nAddress of variable num is: %p", &num);
return 0;
}
Example 1 (cont..)
Output:
Value of variable num is: 10
Address of variable num is: 0x7fff5694dc58 (address may vary)
How to declare a pointer?
int *p1 /*Pointer to an integer variable*/
double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/
 The * operator is also known as value at address operator.
 By using * operator we can access the value of a variable
through a pointer.
How to declare a pointer? (cont..)
double a = 10;
double *p;
p = &a;
*p would give us the value of the variable a.The following statement
would display 10 as output.
printf("%d", *p);
 Similarly if we assign a value to *pointer like this:
*p = 200;
It would change the value of variable a.The statement above will change
the value of a from 10 to 200.
How to declare a pointer? (cont..)
int number ;
int * ptr_to_num ;
number = 23;
ptr_to_num = & number;
printf("Value is %d n", (*ptr_to_num) );
23
number
003F45A8
ptr_to_num
A Simple Example of Pointers in C
#include <stdio.h>
int main(){
int *p;
int var = 10;
p= &var;
printf("Value of variable var is: %d", var);
printf("nValue of variable var is: %d", *p);
printf("nAddress of variable var is: %p", &var);
printf("nAddress of variable var is: %p", p);
printf("nAddress of pointer p is: %p", &p);
return 0;
}
A Simple Example of Pointers in C (cont..)
Output:
Value of variable var is: 10
Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50
NULL Pointer
 A pointer that is assigned NULL is called a null
pointer.
 It is always a good practice to assign a NULL value to
a pointer variable in case we do not have an exact
address to be assigned.
 This is done at the time of variable declaration.
 The NULL pointer is a constant with a value of zero
defined in several standard libraries.
NULL Pointer (cont..)
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %xn", ptr );
return 0;
}
Output: The value of ptr is 0
NULL Pointer (cont..)
 In most of the operating systems, programs are not permitted to
access memory at address 0 because that memory is reserved by
the operating system.
 However, the memory address 0 has special significance; it signals
that the pointer is not intended to point to an accessible memory
location.
 To check for a null pointer, you can use an 'if' statement as follows
−
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Pointers and One-dimensional Arrays
 An array name is a pointer to the first element in the
array.
 So, if x is a one-dimensional array, than the address of
the first element can be expressed as either &x[0] or
simply as x.
 Similarly, the address of the second array element can
be written as either &x[1] or as (x+1).
 In general, the address of the (i+1) array element can
be written as either &x[i] or as (x+i).
Pointers and One-dimensional Arrays
(Example)
#include<stdio.h>
main()
{
static int x[5] = {10,11,12,13,14};
int I;
for(i = 0; i <=4; i++ )
{//display array element
printf(“ni=%d x[i]=%d *(x+i)=%d”,i,x[i], *(x+i));
printf(“ &x[i]=%X x+i=%X”,&x[i], (x+i)); //display address
}
}
Pointers and One-dimensional Arrays
(Example) (cont..)
Output:
i = 0 x[i]=10 *(x+i) = 10 &x[i]=72 x+i= 72
i = 1 x[i]=11 *(x+i) = 11 &x[i]=74 x+i= 74
i = 2 x[i]=12 *(x+i) = 12 &x[i]=76 x+i= 76
i = 3 x[i]=13 *(x+i) = 13 &x[i]=78 x+i= 78
i = 4 x[i]=14 *(x+i) = 14 &x[i]=7A x+i= 7A
 The value of the ith element can be represented by either x[i] or
*(x+i)
 The address of the ith element can be represented by either &x[i] or
(x+i)
Difference Between Pointers and Arrays
Dynamic Memory Allocation
malloc():
 The name "malloc" stands for memory allocation.
 The malloc() function reserves a block of memory of the specified number of bytes.
And, it returns a pointer of type void which can be casted into pointer of any form.
Syntax of malloc():
ptr = (cast-type*) malloc(byte-size)
Example:
ptr = (int*) malloc(100 * sizeof(int));
Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory.
And, the pointer ptr holds the address of the first byte in the allocated memory.
However, if the space is insufficient, allocation fails and returns a NULL pointer.
Dynamic Memory Allocation (cont..)
calloc():
 The name "calloc" stands for contiguous allocation.
 The malloc() function allocates a single block of memory.Whereas, calloc()
allocates multiple blocks of memory and initializes them to zero.
Syntax of calloc()
ptr = (cast-type*) calloc (n, element-size);
Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each
with the size of float.
Dynamic Memory Allocation (cont..)
free():
 Dynamically allocated memory created with either calloc() or
malloc() doesn't get freed on their own.You must explicitly use
free() to release the space.
Syntax of free():
free(ptr);
 This statement frees the space allocated in the memory
pointed by ptr.
Example 1: malloc() and free()
//This program calculates the sum of n numbers entered by the user.
#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));
if(ptr == NULL){
printf("Error! memory not allocated.");
exit(0);
}
Example 1: malloc() and free() (cont..)
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Example 2: calloc() and free()
//This program calculates the sum of n numbers entered by the user.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
Example 2: calloc() and free() (cont..)
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Several Declaration Involving Pointers
 int *p; /* p is a pointer to an integer quantity */
 int *p[10]; /* p is a 10 element array of pointers to
integer quantities */
 int (*p)[10]; /* p is a pointer to a10-element integer
array */
 int *p(void); /* p is a function that returns a pointer
to an integer quantity */
 int p(char *a); /* p is a function that accepts an
argument which is a pointer to a character and returns
an integer quantity */
Several Declaration Involving Pointers (cont..)
 int *p(char *a); /* p is a function that accepts an
argument which is a pointer to a character and
returns a pointer to an integer quantity */
 int (*p)(char *a); /* p is a pointer to a function
that accepts an argument which is a pointer to a
character and returns a pointer to an integer quantity
*/
Applications of Pointer
 Passing Parameter by Reference:
– void interchange(int *num1,int *num2)
– {
– int temp;
– temp = *num1;
– *num1 = *num2;
– *num2 = *num1;
– }
Pointer can be used to simulate passing parameter by
reference. Pointer is used to pass parameter to function.
Applications of Pointer (cont..)
 Accessing Array Element:
int main() {
int a[5] = {1,2,3,4,5};
int *ptr;
ptr = a;
for(i=0;i<5;i++) {
printf("%d",*(ptr+i));
}
return 0;
}
Applications of Pointer (cont..)
 We can access array using pointer.We can store base
address of array in pointer.
ptr = a;
 Now we can access each and individual location using
pointer.
for(i=0;i<5;i++) {
printf("%d",*(ptr+i));
}
Applications of Pointer (cont..)
 Dynamic Memory Allocation: We can use pointer to allocate memory
dynamically. malloc and calloc function is used to allocate memory
dynamically.
int main(){
char *str;
str = (char *) malloc(15);
strcpy(str, "mahesh");
printf("String = %s, Address = %un", str, str);
free(str);
}
 Consider above example where we have used malloc() function to allocate
memory dynamically.
Applications of Pointer (cont..)
 Reducing size of parameter:
struct student {
char name[10];
int rollno;
};
 Suppose we want to pass the above structure to the function
then we can pass structure to the function using pointer in order
to save memory.
 Suppose we pass actual structure then we need to allocate (10 +
4 = 14 bytes(*)) of memory. If we pass pointer then we will
require 4 bytes(*) of memory.
Advantages of Pointer
 Pointers are more efficient in handling Arrays and
Structures.
 Pointers allow references to function and thereby
helps in passing of function as arguments to other
functions.
 It reduces length of the program and its execution
time as well.
 It allows C language to support Dynamic Memory
management.
Lecture 18 - Pointers

Mais conteúdo relacionado

Mais procurados (20)

Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C functions
C functionsC functions
C functions
 
C pointer
C pointerC pointer
C pointer
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
Function & Recursion
Function & RecursionFunction & Recursion
Function & Recursion
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
16 dynamic-memory-allocation
16 dynamic-memory-allocation16 dynamic-memory-allocation
16 dynamic-memory-allocation
 
Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C Language
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresDynamic Memory Allocation, Pointers and Functions, Pointers and Structures
Dynamic Memory Allocation, Pointers and Functions, Pointers and Structures
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
Constructor and Destructor in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++
 
C programming - String
C programming - StringC programming - String
C programming - String
 

Semelhante a Lecture 18 - Pointers

Semelhante a Lecture 18 - Pointers (20)

Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
Pointers
PointersPointers
Pointers
 
See through C
See through CSee through C
See through C
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Module 02 Pointers in C
Module 02 Pointers in CModule 02 Pointers in C
Module 02 Pointers in C
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
Pointers
PointersPointers
Pointers
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
 
Array, string and pointer
Array, string and pointerArray, string and pointer
Array, string and pointer
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Pointer
PointerPointer
Pointer
 

Mais de Md. Imran Hossain Showrov

Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Md. Imran Hossain Showrov
 
Lecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesLecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesMd. Imran Hossain Showrov
 

Mais de Md. Imran Hossain Showrov (20)

Lecture 22 - Error Handling
Lecture 22 - Error HandlingLecture 22 - Error Handling
Lecture 22 - Error Handling
 
Lecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header FileLecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header File
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Lecture 19 - Struct and Union
Lecture 19 - Struct and UnionLecture 19 - Struct and Union
Lecture 19 - Struct and Union
 
Lecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional ArrayLecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional Array
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Lecture 7- Operators and Expressions
Lecture 7- Operators and Expressions Lecture 7- Operators and Expressions
Lecture 7- Operators and Expressions
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language
 
Lecture 4- Computer Software and Languages
Lecture 4- Computer Software and LanguagesLecture 4- Computer Software and Languages
Lecture 4- Computer Software and Languages
 
Lecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesLecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devices
 
Lecture 2 - Introductory Concepts
Lecture 2 - Introductory ConceptsLecture 2 - Introductory Concepts
Lecture 2 - Introductory Concepts
 

Último

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...Nguyen Thanh Tu Collection
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfChristalin Nelson
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEMISSRITIMABIOLOGYEXP
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...Nguyen Thanh Tu Collection
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 

Último (20)

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - I-LEARN SMART WORLD - CẢ NĂM - CÓ FILE NGHE (BẢN...
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdf
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 

Lecture 18 - Pointers

  • 1. Pointers Md. Imran Hossain Showrov (showrovsworld@gmail.com) 18 1
  • 2. Outline  What is a Pointer?  How to declare a pointer?  Pointers and One-dimensional Arrays  Difference Between Pointers and Arrays  Dynamic Memory Allocation  Several Declaration Involving Pointers  Applications of Pointer  Advantages of Pointer
  • 3. What is a Pointer?  Pointers are variables that contain memory addresses as their values.  A variable name directly references a value.  A pointer indirectly references a value. Referencing a value through a pointer is called indirection.  A pointer variable must be declared before it can be used.
  • 4. What is a Pointer? (cont..)  A pointer is a variable that represents the location (rather than the value) of a data item, such as a variable or an array element.  Every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.
  • 5. Example 1  A simple example to understand how to access the address of a variable without pointers? int main() { int num = 10; printf("Value of variable num is: %d", num); printf("nAddress of variable num is: %p", &num); return 0; }
  • 6. Example 1 (cont..) Output: Value of variable num is: 10 Address of variable num is: 0x7fff5694dc58 (address may vary)
  • 7. How to declare a pointer? int *p1 /*Pointer to an integer variable*/ double *p2 /*Pointer to a variable of data type double*/ char *p3 /*Pointer to a character variable*/ float *p4 /*pointer to a float variable*/  The * operator is also known as value at address operator.  By using * operator we can access the value of a variable through a pointer.
  • 8. How to declare a pointer? (cont..) double a = 10; double *p; p = &a; *p would give us the value of the variable a.The following statement would display 10 as output. printf("%d", *p);  Similarly if we assign a value to *pointer like this: *p = 200; It would change the value of variable a.The statement above will change the value of a from 10 to 200.
  • 9. How to declare a pointer? (cont..) int number ; int * ptr_to_num ; number = 23; ptr_to_num = & number; printf("Value is %d n", (*ptr_to_num) ); 23 number 003F45A8 ptr_to_num
  • 10. A Simple Example of Pointers in C #include <stdio.h> int main(){ int *p; int var = 10; p= &var; printf("Value of variable var is: %d", var); printf("nValue of variable var is: %d", *p); printf("nAddress of variable var is: %p", &var); printf("nAddress of variable var is: %p", p); printf("nAddress of pointer p is: %p", &p); return 0; }
  • 11. A Simple Example of Pointers in C (cont..) Output: Value of variable var is: 10 Value of variable var is: 10 Address of variable var is: 0x7fff5ed98c4c Address of variable var is: 0x7fff5ed98c4c Address of pointer p is: 0x7fff5ed98c50
  • 12. NULL Pointer  A pointer that is assigned NULL is called a null pointer.  It is always a good practice to assign a NULL value to a pointer variable in case we do not have an exact address to be assigned.  This is done at the time of variable declaration.  The NULL pointer is a constant with a value of zero defined in several standard libraries.
  • 13. NULL Pointer (cont..) #include <stdio.h> int main () { int *ptr = NULL; printf("The value of ptr is : %xn", ptr ); return 0; } Output: The value of ptr is 0
  • 14. NULL Pointer (cont..)  In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system.  However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location.  To check for a null pointer, you can use an 'if' statement as follows − if(ptr) /* succeeds if p is not null */ if(!ptr) /* succeeds if p is null */
  • 15. Pointers and One-dimensional Arrays  An array name is a pointer to the first element in the array.  So, if x is a one-dimensional array, than the address of the first element can be expressed as either &x[0] or simply as x.  Similarly, the address of the second array element can be written as either &x[1] or as (x+1).  In general, the address of the (i+1) array element can be written as either &x[i] or as (x+i).
  • 16. Pointers and One-dimensional Arrays (Example) #include<stdio.h> main() { static int x[5] = {10,11,12,13,14}; int I; for(i = 0; i <=4; i++ ) {//display array element printf(“ni=%d x[i]=%d *(x+i)=%d”,i,x[i], *(x+i)); printf(“ &x[i]=%X x+i=%X”,&x[i], (x+i)); //display address } }
  • 17. Pointers and One-dimensional Arrays (Example) (cont..) Output: i = 0 x[i]=10 *(x+i) = 10 &x[i]=72 x+i= 72 i = 1 x[i]=11 *(x+i) = 11 &x[i]=74 x+i= 74 i = 2 x[i]=12 *(x+i) = 12 &x[i]=76 x+i= 76 i = 3 x[i]=13 *(x+i) = 13 &x[i]=78 x+i= 78 i = 4 x[i]=14 *(x+i) = 14 &x[i]=7A x+i= 7A  The value of the ith element can be represented by either x[i] or *(x+i)  The address of the ith element can be represented by either &x[i] or (x+i)
  • 19. Dynamic Memory Allocation malloc():  The name "malloc" stands for memory allocation.  The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form. Syntax of malloc(): ptr = (cast-type*) malloc(byte-size) Example: ptr = (int*) malloc(100 * sizeof(int)); Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. However, if the space is insufficient, allocation fails and returns a NULL pointer.
  • 20. Dynamic Memory Allocation (cont..) calloc():  The name "calloc" stands for contiguous allocation.  The malloc() function allocates a single block of memory.Whereas, calloc() allocates multiple blocks of memory and initializes them to zero. Syntax of calloc() ptr = (cast-type*) calloc (n, element-size); Example: ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of float.
  • 21. Dynamic Memory Allocation (cont..) free():  Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own.You must explicitly use free() to release the space. Syntax of free(): free(ptr);  This statement frees the space allocated in the memory pointed by ptr.
  • 22. Example 1: malloc() and free() //This program calculates the sum of n numbers entered by the user. #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)); if(ptr == NULL){ printf("Error! memory not allocated."); exit(0); }
  • 23. Example 1: malloc() and free() (cont..) printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; }
  • 24. Example 2: calloc() and free() //This program calculates the sum of n numbers entered by the user. #include <stdio.h> #include <stdlib.h> int main() { int n, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &n); ptr = (int*) calloc(n, sizeof(int)); if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); }
  • 25. Example 2: calloc() and free() (cont..) printf("Enter elements: "); for(i = 0; i < n; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; }
  • 26. Several Declaration Involving Pointers  int *p; /* p is a pointer to an integer quantity */  int *p[10]; /* p is a 10 element array of pointers to integer quantities */  int (*p)[10]; /* p is a pointer to a10-element integer array */  int *p(void); /* p is a function that returns a pointer to an integer quantity */  int p(char *a); /* p is a function that accepts an argument which is a pointer to a character and returns an integer quantity */
  • 27. Several Declaration Involving Pointers (cont..)  int *p(char *a); /* p is a function that accepts an argument which is a pointer to a character and returns a pointer to an integer quantity */  int (*p)(char *a); /* p is a pointer to a function that accepts an argument which is a pointer to a character and returns a pointer to an integer quantity */
  • 28. Applications of Pointer  Passing Parameter by Reference: – void interchange(int *num1,int *num2) – { – int temp; – temp = *num1; – *num1 = *num2; – *num2 = *num1; – } Pointer can be used to simulate passing parameter by reference. Pointer is used to pass parameter to function.
  • 29. Applications of Pointer (cont..)  Accessing Array Element: int main() { int a[5] = {1,2,3,4,5}; int *ptr; ptr = a; for(i=0;i<5;i++) { printf("%d",*(ptr+i)); } return 0; }
  • 30. Applications of Pointer (cont..)  We can access array using pointer.We can store base address of array in pointer. ptr = a;  Now we can access each and individual location using pointer. for(i=0;i<5;i++) { printf("%d",*(ptr+i)); }
  • 31. Applications of Pointer (cont..)  Dynamic Memory Allocation: We can use pointer to allocate memory dynamically. malloc and calloc function is used to allocate memory dynamically. int main(){ char *str; str = (char *) malloc(15); strcpy(str, "mahesh"); printf("String = %s, Address = %un", str, str); free(str); }  Consider above example where we have used malloc() function to allocate memory dynamically.
  • 32. Applications of Pointer (cont..)  Reducing size of parameter: struct student { char name[10]; int rollno; };  Suppose we want to pass the above structure to the function then we can pass structure to the function using pointer in order to save memory.  Suppose we pass actual structure then we need to allocate (10 + 4 = 14 bytes(*)) of memory. If we pass pointer then we will require 4 bytes(*) of memory.
  • 33. Advantages of Pointer  Pointers are more efficient in handling Arrays and Structures.  Pointers allow references to function and thereby helps in passing of function as arguments to other functions.  It reduces length of the program and its execution time as well.  It allows C language to support Dynamic Memory management.