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

Unit - 4 Pointers

c programming pointers

Uploaded by

Chandrika Surya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Unit - 4 Pointers

c programming pointers

Uploaded by

Chandrika Surya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit-4

A Pointer is a constant or variable that contains an address that can be used to access data. (or) A
pointer is a variable that can contain or hold the address of another variable.
 If a pointer is a constant, its value cannot be changed. That means we cannot change pointer
constants and we can only use them.
 The address of a variable is the address of the first byte occupied by that variable.
 The following picture shows integer variables and their address:

address
234560
a 123

Variabl
e name Integer
value

 The address operator (&) extracts the address for a variable. The format of address operator
is shown below:
& variablename;

 To print the addresses of variables, we use “%p” as conversion code.

Pointer variables:
 Pointer variables are used to store the addresses of the other variables. The following figure
shows this concept:
Address of
234560 variable
a 123
‘a’ &a stored
p 234560
in variable

 The above concept can be logically represented as follows:


Variable Pointer
name Integer Variable name
value

a 123

Pointer declaration & definition:


 We use the asterisk (*) symbol to declare pointer variables. The declaration syntax for a
pointer variable is given below:

 Example: datatype* identifier;


char* p;
int* q;
float* r;
Initialization of pointer variables:
 Uninitialized pointers will have some unknown memory address in them.
 The following figure shows an uninitialized variable and an uninitialized pointer.
 We must always assign a valid memory address to the pointer. It is also possible to initialize
pointers when they are declared & defined.
 The following is an example for declaring and initializing an integer pointer:

Pointers Page 1
Unit-4

int a=10;

int* p = &a;

Int *p; p = &a;

declaration initialization

 The above figure shows the initialization of pointer variable involves two steps. First the
variable is declared & then assigns a value to it.
Accessing variables through pointers:
 To access the contents of variables through pointers, we can use “indirection operator (*)”.
 The indirection operator is a unary operator whose operand must be a pointer value.
 Syntax:
*pointername;
 Note that the indirection (*) and address (&) operators are the inverse of each other. That
means the expression *(&x) gives the value of the variable ‘x’. (& and * cancel each other).
/* Program to access variables through pointers*/
#include<stdio.h>
main(){
int a=10;
int* ptr=&a;
printf("\n Address of a: %p", ptr);
printf("\n Address of a : %p", &a);
printf("\n a: %d", a);
printf("\n a through pointer : %d", *ptr);
}
Output:

Address of a: 0022FF18
Address of a : 0022FF18
a: 10
a through pointer : 10

Uses of Pointers:
Pointers have many uses in C.
 Pointers provide efficient techniques for manipulating data in arrays.
 Pointers are used in functions to pass the addresses as parameters.
 Pointers are the basis for dynamic memory allocation.

Pointer Expression and Pointer Arithmetic or Address Arithmetic:


 Like other variables, pointer variables can be used in expressions. If an expression contains
pointer variable then it is called pointer expression.
 It allows us to do subtract one pointer from another pointer. i.e.. It subtracts the addresses of the
two pointer variables and then divides it by the size of the pointer
 It does not allow us to do Addition, multiplication and division of two pointers( two addresses).
 It allow us to do increment and decrement operation on pointers. It increments the address stored by
the pointer by the size of its data type and it decrements the address stored by the pointer by the size
of its data type.
 Scale factor is possible on pointers. Pointers allow us to increase or decrease its value by the length of
data type that it points to. This length is called scale factor.

/*Program for pointer arithmetic */

Pointers Page 2
Unit-4
#include <stdio.h>
main()
{
int a=10,b=20;
int *p1=&a;
int *p2=&b;
int *p3;
printf("p1 = %d\n", p1);
printf("p2 = %d\n", p2);
printf("size of p1=%d\n",sizeof(p1));
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3);
p1++;
printf("p1++ = %d\n", p1);
p2--;
printf("p2-- = %d\n", p2);
p2=p2+3;
printf("p2 = %d\n", p2);
}
Output:

Types of pointers

NULL Pointer:
 A pointer variable that can be initialized with NULL value is called NULL Pointer. That means
we can assign a null value to a pointer as follows:
int* NULL;
Void Pointer:
 A void pointer is a special pointer that can point to object of any type.
 A void pointer is type less pointer also known as generic pointer.
 void pointer is an approach towards generic functions and generic programming in C.
 Syntax : void * pointername;

/*Program for void pointer*/


#include <stdio.h>
main()
{
int a = 10;
void * p = &a; // void pointer pointing at num
printf(" a=%d",a);
printf("\n a through void pointer =%d",*(int*)p );
}
Output:
a=10
a through void pointer =10

Wild Pointer

Pointers Page 3
Unit-4

 It is also called as uninitialized pointers.


 It point to some arbitrary(unknown) memory location and may cause a program to crash or
behave badly.
 It is advised to be cautious while working with wild pointers.
/*Program for Wild pointer*/
#include <stdio.h>
main()
{
int* p; // Wild pointer
printf("%d",*p);
}

Pointers to Pointers:
 We can also declare a pointer to another pointer variable.
 A pointer to pointer is a variaible which stores the address of another pointer.
 Syntax: datatype ** pointename;
 Example: this is a two level indirection
int a=10;
246889 124680 234560
int * p=&a;
int ** q=&p; 124680 234560 10
q p a
/* program to demonstrate pointer to pointer*/
#include <stdio.h>
main()
{
int a = 10;
int * p=&a;
int ** q=&p;
printf("\n a=%d",a);
printf("\n a through pointer p=%d",*p);
printf("\n a through pointer q=%d",**q);
}
Output:
a=10
a through pointer p=10
a through pointer q=10

Dynamic Memory Allocation:


 C gives us two choices when we want to reserve memeory locatios for an object
1. Static allocation 2. Dynamic allocation
 Static memory allocation requires that the declaration & definition of memory be fully specified
in the source program and the memory will be allocated in ‘stack memory’.
 In static memory allocation, the number of bytes reserved cannot be changed during runtime.
 Dynamic memory allocation uses pre-defined functions to allocate and release memory for
data while the program is running.
 In dynamic memory allocation, the memory will be allocated in ‘heap memory’.
 We can refer to the memory allocated in the heap only through a pointer.
 To access data in a dynamic memory, we must use a pointer. So we say that the pointers are
the basis for dynamic memory allocation.
 The following figure shows the difference between static & dynamic memory allocation
techniques:

Pointers Page 4
Unit-4

int* x;
-----------
int x;
-----------
-------- x=malloc(…)
-------- x -----------
-------- ----------- x
--------
--------

Stack Heap
Stackk

Static memory allocation Dynamic memory allocation

Memory allocation functions:


There are four memory allocation functions for allocating memory dynamically in C. They are:
i) malloc()
ii) calloc()
iii) realloc()
iv) free()
 The first three functions are used for memory allocation and the fourth function (free()) is used
to return the memory when it is no longer needed.
 These memory allocation functions are found in ‘stdlib.h’ header file.
 The following figure shows the memory management functions in C:

Memory
Management

Memory Memory
Allocation De allocation

malloc()
free()
calloc()

realloc()

i) malloc():
 The ‘malloc()’ function allocates a block of memory that contains the number of bytes
specified in its parameter.
 The allocated memory is not initialized.
 Syntax: void* malloc(size_t size);

 The malloc() function returns the address of first byte in the memory space allocated.
 It returns a NULL pointer on failure.
 The following code shows how can we create dynamic array using malloc() function:
int* arr;
int n;
printf(“\n Enter size of the array: ”);
scanf(“%d”, &n);
arr=(int*) malloc(n*sizeof(int));

Pointers Page 5
Unit-4
ii) calloc():
 The ‘calloc()’ function also allocates the memory similar to malloc() function.
 It differs from malloc() in one way. The calloc() function initializes the allocated memory with
nulls.
 Syntax: void* calloc(size_t count, size_t size);
 It allocates memory equal to count * size bytes and returns starting byte address.
 It returns a null pointer on failure.
 The following piece of code shows how we create a dynamic array using calloc() function:

int* arr;
int n;
printf(“\n Enter size of the array: ”);
scanf(“%d”, &n);
arr=(int*) calloc(n,sizeof(int));
iii) realloc():
 The ‘realloc()’ function is for reallocation of memory.
 This function changes the size of the block by deleting or extending the memory at the end of
the block.
 If the memory cannot be extended, realloc() allocates a completely new block and copies the
existing memory allocation to the new allocation & deletes the old allocation.
void* realloc(void* ptr, size_t size);
 Syntax:
 Here ‘ptr’ is a pointer that points to the memory allocated previously by malloc() or calloc()
function.
 The ‘size’ specifies the new size of the memory that is to be reallocated.
 The realloc() function returns a NULL pointer on failure.

iv) free():
 When the memory locations allocated by malloc(), calloc() or realloc() are no longer needed,
they should be freed.
 The free() function helps you to release the allocated memory.
 Syntax:
void free(void* ptr);
 Here ‘ptr’ is a pointer that points to the memory previously allocated by malloc() or calloc()
function.
 The pointer used to free memory must be of the same type as the pointer used to allocate the
memory.

Write a c program tofind sum of elements entered by user. To perform this


program, allocate memory dynamically using malloc() function.

#include<stdio.h>
main(){
int n, i,sum=0;
int *arr;
printf("\n Enter the size of the array: ");
scanf("%d", &n);
arr=(int*) malloc(n*sizeof(int)); /* dynamic memory allocation */
printf("\n Enter elements: ");
for(i=0; i<n; i++)
scanf("%d", arr+i);
printf("\n Elements are . . . . \n");
for(i=0; i<n; i++)
{
printf("%d\t", *(arr+i));
sum=sum+(*(arr+i));
}
printf("\n Sum of array elements are=%d",sum);
free(arr); /* to de allocate memory */
}

Pointers Page 6
Unit-4
Output:

Write a c program tofind sum of elements entered by user. To perform this


program, allocate memory dynamically using calloc() function.

#include<stdio.h>
main(){
int n, i,sum=0;
int *arr;
printf("\n Enter the size of the array: ");
scanf("%d", &n);
arr=(int*) calloc(n, sizeof(int)); /* dynamic memory allocation */
printf("\n Enter elements: ");
for(i=0; i<n; i++)
scanf("%d", arr+i);
printf("\n Elements are . . . . \n");
for(i=0; i<n; i++)
{
printf("%d\t", *(arr+i));
sum=sum+(*(arr+i));
}
printf("\n Sum of array elements are=%d",sum);
free(arr); /* to de allocate memory */
}
Output:

Pointers and Arrays:


 When an array is declare, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory locations.
 The base address is the location of the first element(index 0) of the array.
 The compiler also defines the array name as a constant pointer to the first elemet.
Pointer to 1-D Array:
Let int a[5]={10,20,30,40,50};
Suppose the base address of a is 2000 and assuming that each integer requires two bytes, the
given array has five elements which needs 10 bytes of memory and will be stored as follows:

Pointers Page 7
Unit-4

Elements → a[0] a[1] a[2] a[3] a[4]


Values → 10 20 30 40 50
Address → 2000 2002 2004 2006 2008

Base address

The name a defined as a constant pointer pointing to the first elemet, a[0] and therefor the
value of a is 2000, the location where a[0] is stored. i.e., a=&a[0]=2000.
If we declare p as integer pointer, then we can make the pointer p point to the array a:
int *p=&a[0] /* int *p= a */
now we can access every element of an array through pointer.
i.e., p=&a[0]
p+1=&a[1]
p+2=&a[2]
p+3=&a[3]
p+4=&a[4]
*(p+1) gives value ofa[1]

/* program to demonstrate pointer and 1-D array*/


#include <stdio.h>
main()
{
int a[5] = {10,20,30,40,50};
int * p=&a;
int sum=0,i;
printf("\n Array elements are\n");
for(i=0;i<5;i++)
{
printf(" %d\t",*(p+i));
sum=sum+ (*(p+i));
}
printf("\n sum of given array elements are=%d",sum);
}
Output:
Array elements are
10 20 30 40 50
sum of given array elements are=150

Pointer to 2-D Array:


 The name of the two-dimensional array is also the constant pointing the first element of the
array.
 A two-dimensional array is the array of one-dimensional arrays. So, the first element of the
two-dimensional array is just another array.
 Let us consider the following 2-D array:
int a[3][4];

a[0]

a[1] rows

a[2]

a[3][4];

Pointers Page 8
Unit-4
 int *p =&a[0][0];
 p is a pointer now pointer to 2-D array which points first row of a 2 D Array.
 p++ is used to move from one element to another element of an pointer.
 We can also use double dereference *(*(a+i)+j) to access elements of an array.
/* program to demonstrate pointer and 2 D array*/
#include <stdio.h>
main()
{
int a[3][4] = {10,20,30,40,50,60,70,80,90,100,110,120};
int * p=&a[0][0];
int i,j;
printf("\n Array elements are\n");
for(i=0;i<12;i++)
{
printf(" %d\t",*(p+i));
}
printf("\n Array elements are\n");
for(i=0;i<3;i++)
{ for(j=0;j<4;j++)
{
printf(" %d\t", *(*(a+i)+j));
}
}
}
Output:

Array elements are


10 20 30 40 50 60 70 80 90
100 110 120
Array elements are
10 20 30 40 50 60 70 80 90
100 110 120

Dangling Memory and Dangling pointer:


 A common logical mistake occurs in functions is that sometimes we may unable to access the
memory which is allocated at our request. This is known as ‘Dangling memory problem’.
 Dangling pointer is also a pointer which points to a memory which is not currently in our
account.
 Any attempt to access the information in the memory pointed by a dangling pointer will lead to
memory segment violation.
 This memory segment violation occurs usually because of user’s mistake.

/* program to demonstrate dangling pointer problem */

#include<stdio.h>
#include<stdlib.h>
main()
{
char* p;
p=(char*)malloc(80);
printf("\n Enter a string: ");
gets(p);
printf("\n Address of string: %p",p);
printf("\n String is %s",p);
free(p);
printf("\n Address of the string: %p", p);
printf("\n String is: %s", p);
}

Pointers Page 9
Unit-4
Output:
Enter a string: scet ece
Address of string: 003D1040
String is scet ece
Address of the string: 003D1040
String is: H1=
Command line arguments:
 It is possible to pass arguments to C programs when they are executed. These arguments
are known as “Command-line arguments”.
 The ‘main()’ function may also has parameters and these parameters are called command-
line arguments.
 Command line arguments are the arguments which are passed to function at the runtime.
 The following is the declaration of ‘main()’ function:

void main(int argc, char *argv[])

 main() function two arguments: first argument ‘argc’ refers to the number of arguments
passed and second argument ‘argv[]’ refers to a pointer array which points to each
argument.
 The ‘argc’ value is not entered using the keyboard. The system determines it from the
arguments the user types.
 The general form of Command line arguments:

void main(void){ void main(int argc, char* argv[]){

--------- ---------

--------- ---------

--------- ---------

} }

Without With command-line arguments


command-line
arguments

Write a c program to perform addition, subtraction, multiplication and


division of two numbers using command line arguments
#include <stdio.h>
int main(int argc, char** argv)
{
int a,b,c,d;
a=atoi(argv[1])+atoi(argv[2]);
b=atoi(argv[1])-atoi(argv[2]);
c=atoi(argv[1])*atoi(argv[2]);
d=atoi(argv[1])/atoi(argv[2]);
printf("\n Addition is %d",a);
printf("\n Subtraction is %d",b);
printf("\n Multiplication is %d",c);
printf("\n Division is %d",d);
return 0;
}
Output:

Pointers Page 10
Unit-4

Write a c program to demonstrate realloc function.

#include <stdio.h.>
#include<stdlib.h>
main()
{
int i,n,*ptr,*ptr1,m;
printf("Enter size:");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
printf("\nEnter %d elements:",n);
for(i=0;i<n;i++)
{
scanf("%d",(ptr+i));
}
printf("Entered elements are:\n");
for(i=0;i<n;i++)
{
printf("%d\t",*(ptr+i));
}
printf("\n Enter updated size:");
scanf("%d",&m);
ptr1=(int*)realloc(ptr,m*sizeof(int));
printf("Enter updated elements:\n");
for(i=n;i<m;i++)
{
scanf("%d",(ptr1+i));
}
printf("Entered elements are:");
for(i=0;i<m;i++)
{
printf("%d\t",*(ptr1+i));
}
free(ptr1);
}

Output:

Pointers Page 11
Unit-4

Pointers Page 12

You might also like