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

CH 8 Pointer

Uploaded by

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

CH 8 Pointer

Uploaded by

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

C- Programming

Sujan Karki
Email: sujan074bct045@ioepc.edu.np
Contact No.: 9819387234
Master’s in Information System Engineering (MscIne) *Ongoing
Bachelor in Computer Engineering – Purwanchal Campus,IOE
UNIT 7

POINTER

2
POINTER
⚫ A pointer is a variable that stores the address of
another variable.
⚫ The address of a data item is a pointer to the data
item, and a variable that holds the address is called a
pointer variable.

Some uses of pointers are:


⚫ Accessing array elements.
⚫ Returning more than one value from a function.
⚫ Accessing dynamically allocated memory.
⚫ Implementing data structures like linked lists, trees,
3
and graphs.
Address (&) Operator and
indirection/dereference (*) operator
⚫ C provides an address operator “&‟, which returns
the address of a variable when placed before it. This
operator can be read as “the address of”, so &age
means address of age, similarly &sal means address of
sal.
⚫ We can access a variable indirectly using pointers. For
this we will use the indirection operator (*). By
placing the indirection operator before a pointer
variable, we can access the variable whose address is
stored in the pointer.
⚫ &: Address of
4
⚫ * : value at address of
⚫ Example:

#include<stdio.h>
int main() {
int age=25, *page;
float sal=50000,*psal;
page=&age;
psal=&sal;
printf("\nAddress of age=%d and value of age=%d", page,*page);
printf("\nAddress of sal=%d and value of sal=%f", psal,*psal);
}

OUTPUT:
Address of age=666708124 and value of age=25
Address of sal=666708120 and value of sal=50000.000000

5
Declaration of pointer
⚫ Like all other variables it also has a name, has to be declared
and occupies some space in memory. It is called pointer
because it points to a particular location in memory by storing
the address of that location.
Syntax:
datatype *identifier
e.g. int age; //declaring a normal variable
int *ptr; //declaring a pointer variable
ptr=&age; //store address of the variable age in the variable ptr.
· Now ptr points to age or ptr is a pointer to age.
· We created a pointer ptr which becomes a variable that
contains the address of another variable age.

6

int age;
float *ptr;
ptr=&age; //invalid
Bad pointer:
A bad pointer is one that points to the wrong object, or no object
at all. Dereferencing such a pointer will access the wrong object
or may crash the program. Hence, each pointer must be assigned
a valid address before dereferencing it.
Void Pointer:
A void pointer is a special type of pointer which can point to
variable of any data type i.e. int, float, char etc. Using void
pointer , the pointed data cannot be directly referenced. The type
casting must be used to change the void pointer to specific data
type to which we are referring.
7

#include<stdio.h>
int main() {
int v = 7;
float w = 7.6;
void *u;
u = &v;
printf(“The Integer variable in the program is equal to = %d”,
*( (int*) u) );
u = &w;
printf(“\n The Float variable in the program is equal to = %f”,
*( (float*) u) );
return 0;
}

8
Null pointer:
A NULL pointer is a special pointer value that points nowhere or
nothing in the memory address. e.g. int *ptr= NULL;
Pointer arithmetic:
All types of arithmetic operations are not possible with pointers.
The only valid operations that can be performed are as:
1. Addition of an integer to a pointer and increment operation.
2. Subtraction of an integer from a pointer and decrement
operation.
3. Subtraction of a pointer from another pointer of same type.
e.g. if we have an int pointer pi which contains address 1000 then
on incrementing we get 1002 instead of 1001 because the size of
int data type is 2. Similarly on decrementing pi, we will get 998
instead of 999. The expression (pi + 3) will represent the address
1006.
9

Program to understand pointer arithmetic
#include<stdio.h>
void main() {
int a=5,*pi; float b=7.3,*pf; char c='x',*pc;
pi=&a;
pf=&b;
pc=&c;
printf("\n Address of a=%u ",pi);
printf("\n Address of b=%u ",pf);
printf("\n Address of c=%u ",pc);
pi++;
pf++;
pc++;
printf("\n\n Address of a=%u ",pi);
printf("\n Address of b=%u ",pf);
printf("\n Address of c=%u ",pc);
10 }
The arithmetic operations that can never be performed on
pointers are:
1. Addition, multiplication, division of two pointers.
2. Multiplication between pointer and any number.
3. Division of a pointer by any number.
4. Addition of float or double values to pointers.

11
⚫ Example:
#include<stdio.h> Output:
void main( ) 1
{ 1
int x[15]= {1,26,3,4,5}; 1
int *p; 27
p= &x[0]; or p=x; 0
printf(“%d” , x[0]); 27
printf(“%d” , *p); On separate:
printf(“%d” , *p++); 1
printf(“%d” , ++*p); 1
printf(“%d” , *(p+4)); 1
p=&x[2]; 2
printf(“%d” , *(p-1)); 5
} 26
12
Pointer to Pointer (double indirection)
Pointer variable itself might be another pointer so
pointer which contains another pointer’s address is
called pointers to pointers or multiple indirections.
Syntax :
datatype **identifier;
e.g. int **pptr;
void main() {
int a=5,*pa,**ppa;
pa=&a;
ppa=&pa;
printf("\n Value of a=%d",*pa);
printf("\n Value of a=%d",**ppa);
13
}
Arrays of pointer
The multiple pointers of same types can be represented by
an array. Each element of such array represent pointer and
they can point to different locations.
Syntax:
Data_type *pointer_name[size]
Example: int *p[10];
Here p is an array of pointer each of which points to an
integer. The first pointer is p[0], second is p[1] and so on.
Initially they are uninitialized.
int a=10m b=100 ,c=200;
p[0]= &a;
p[1]= &b;
p[2]= &c; and so on.
14
Pointer and 2-d array
Syntax:
Data_type [*ptr_variable] [size2];
Normally, in array data_type array_name[size1] [size2];
e.g. int [*x] [5]; rather than int [4] [5];
x
*x *x+1 *x+2 *x+3 *x+4

x+1
*(x+1) *(x+1)+1 *(x+1)+2 *(x+1)+3 *(x+1)+4

x+2
*(x+2) *(x+2)+1 *(x+2)+2 *(x+2)+3 *(x+2)+4
15

It can be summarized as:
x= pointer to 1st row
x+i= pointer to i row
*(x+i)= pointer to first element in the i row
*(x+i)+j = pointer to j element in the i row
*(*(x+i) +j)= value stored in the cell i, j
Thus in 2 D array:
&x[0] [0] = *x or *(x+0) +0
&x[0] [1] = *x+1 or *(x+0) +1
&x[2] [0] = *(x+2) or *(x+2) +0
&x[2] [4] = *(x+2) +4
And
x[0] [0] = **x or *(*(x+0) +0)
x[0] [1] = *(*x+1) or *(*(x+0) +1)
x[2] [0] = *(*(x+2)) or *(*(x+2) +0)
x[2] [4] = *(*(x+2) +4)

16
⚫ Example:
#include<stdio.h>
OUTPUT:
void disp(int *p) { 1
printf(“%d” , *p); 4
printf(“%d” , *(p+3));
}

void main( )
{
int a[]= {1,2,3,4,5};
disp(&a);
}

17
⚫ Example:
#include<stdio.h>

void addGraceMarks(int *m) {


*m = *m+10;
}
void main( ) {
int marks;
printf(“Enter actual marks: It”);
scanf(“%d”,&marks);
add GraceMarks(&marks);
printf(“\n Te graced marks is:
\t%d”, marks);

18
}
⚫ Example:
#include<stdio.h> void version(char *c) {
void version(char *c); if(*c>=97 && *c<=122)
int main( ) { {
char inp; *c=*c-32;
printf("enter character of your }
choice"); else(*c>=65 && *c<=90)
scanf("%c", &inp); {
version(&inp); *c=*c+32;
printf("The character now is %c", }
inp); }
return 0; Note: The change made by the function would be
} done to the local variables of the function. When
we use pointers, the value is changed at the
address of variable

19
String and Pointer
Let’s compare the strings defined as arrays and strings defined as pointers.
char str[]=“Chitwan”;
char *ptr=“Nawalparasi”;
These two forms may look similar but there are some differences in them. The
initialization itself has different meaning in both forms. In array form,
initialization is a short form for-
char str[]={‘C’, ‘h’, ‘i’, ‘t’, ‘w’, ‘a’, ‘n’, ‘\0’}
while in pointer form, address of string constant is assigned to the pointer
variable. Now let us see how they are represented in memory.

20
Array of pointer with string
Array of pointers to strings is an array of char pointers in which each pointer
points to the first character of a string i.e. each element of this array contains
the base address of a string.
char *arrp[]={“white”,”red”,”green”,”yellow”,”blue”};
Here arrp is an array of pointers to string.

21
Dynamic Memory allocation
The memory allocation that we have done till now was static memory
allocation. The memory that could be used by the program was fixed i.e.
we could not increase or decrease the size of memory during the execution
of program. e.g. int emp[100]; Now two types of problems may occur.
1. The number of values to be stored is less than the size of array then
there will be the wastage of memory.
2. If we want to store more values than the size of array then we can’t.
To overcome these problems we should be able to allocate memory at run
time. The process of allocating
memory at the time of execution is called dynamic memory allocation. The
allocation and release of this
memory space can be done with the help of some built-in-functions whose
prototypes are found in alloc.h and
stdio.h header files.

22
Dynamic Memory allocation
1. malloc ( )
This function is used to allocate memory dynamically.
syntax:
pointer_variable=(datatype*) malloc(specified_size);
Here pointer_variable is a pointer of type datatype, and specified_size is
the size in bytes required to be reserved in memory.

2. calloc ( )
The calloc ( ) function is used to allocate multiple blocks of memory. It is
somewhat similar to malloc ( ) function except for two differences. The
first one is that it takes two arguments. The first argument specifies the
number of blocks and the second one specifies the size of each block. For
example: ptr= (int *) calloc (5, sizeof(int));
The other difference between calloc( ) and malloc( ) is that the memory
allocated by malloc( ) contains garbage value while the memory allocated
by calloc( ) is initialized to zero.
23
Dynamic Memory allocation
3. realloc( )
The function realloc( ) is used to change the size of the memory block. It
alters the size of the memory block without losing the old data. This is
known as reallocation of memory.
This function takes two arguments, first is a pointer to the block of
memory that was previously allocated by malloc( ) or calloc( ) and second
one is the new size for that block.
For example
ptr=(int*) realloc (ptr,newsize);

24
25
26
Dynamic Memory allocation
Program to understand dynamic allocation of memory.
#include<stdio.h>
#include<alloc.h>
void main() {
int *ptr, n, i;
printf("How many numbers do you want to entered: ");
scanf("%d", &n);
ptr=(int *)malloc(n*sizeof(int));
for(i=0;i<n; i++) {
printf("\n Enter number: ");
scanf("%d", ptr+i);
}
printf("\n Displaying elements: ");
for(i=0;i<n; i++) {
printf("\n%d",*(ptr+i));
}
27
}
. . . to be continued !!!

28

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy