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

Lecture 18 - Pointers

  • 1.
    Pointers Md. Imran HossainShowrov (showrovsworld@gmail.com) 18 1
  • 2.
    Outline  What isa 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 aPointer?  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 aPointer? (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  Asimple 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: Valueof variable num is: 10 Address of variable num is: 0x7fff5694dc58 (address may vary)
  • 7.
    How to declarea 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 declarea 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 declarea 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 Exampleof 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 Exampleof 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  Apointer 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-dimensionalArrays  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-dimensionalArrays (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-dimensionalArrays (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)
  • 18.
  • 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 InvolvingPointers  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 InvolvingPointers (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.