Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
MODULE 2
Pointers
pointers to array
Pointer and functions
Pointer to strings
Array of pointers
pointers to pointers
Dynamic memory allocation
Dereferencing Address
(Value of)
&(Address of)
‘&i’ variable
i
‘*i’
3
(Value of i)
Address of i
The value ‘3’Powerpoint
is saved in the memory location ‘x100c’
Templates Page 6
Declaring a Pointer
• General syntax of pointer declaration is
data_type *pointer_name;
• Rule:
Data type of pointer must be same as the variable, which the
pointer is pointing.
• Note:
void data type pointer works with all data types, but its not used
oftenly.
int a, *p;
a = 10;
p = &a;
printf(“%d”, *p);
printf(“%d”, *&a);
printf(“%u”, &a);
printf(“%u”, p);
printf(“%u”, &p);
Powerpoint Templates Page 10
Dereferencing Operator *
• We can access to the value stored in the variable pointed to by using the dereferencing
operator (*),
… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
#include<stdio.h>
Void main()
{
Int i=3;
Int *j;
j=&i;
Printf(“i=%d”i);
Printf(“*j=%d”*j);
} Powerpoint Templates Page 12
Int i=3; Create an integer variable ‘i’ and initialize it to 3
variables
Int *j Int i
M
e 3
m x100c
or
y
Int *j Int i
M
e 33
m x100c
or
y
X1000 x1004 x1008
Powerpoint Templates x100c x1010 x1014
Page 14
Example : Sum of two numbers using Pointers
#include <stdio.h>
main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
}
Powerpoint Templates Page 15
Predict the output of this code
Void main()
{
int num=10;
int* pnum=NULL;
pnum = #
*pnum += 20;
printf("\nNumber = %d", num);
printf("\nPointer Number = %d", *pnum);
}
Powerpoint Templates Page 16
Number = 10
Pointer Number = 30
a 2 p - 1
a + 1 4 p
a + 2 6 p + 1
a + 3 8 p + 2
a + 4 22 p + 3
58 58 58