FCP 5 Pointers
FCP 5 Pointers
Function
Recursion
Write a C program to find sum of first n natural numbers
using recursion. Note: Positive integers are known as
natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
=sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Pointers
Introduction
First of all, it is variable, just like other variables you
studied.
– so it has type, storage etc.
A pointer is a variable that represents the location (rather
than the value) of a data item.
Difference: it can only store the address (rather than the
value) of a data item.
They have a number of useful applications.
– Enables us to access a variable that is defined
outside the function.
– Can be used to pass information back and forth
between a function and its reference point.
– More efficient in handling data tables.
– Reduces the length and complexity of a program.
– Sometimes also increases the execution speed.
Basic Concept
In memory, every stored data item occupies one or more
contiguous memory cells.
– The number of memory cells required to store a
data item depends on its type (char, int, double, etc.).
1 1.2 C
Xyz Variable
50 Value
1380 address
Contd.
During execution of the program, the system always
associates the name xyz with the address 1380.
– The value 50 can be accessed by using either the name
xyz or the address 1380.
Since memory addresses are simply numbers, they can be
assigned to some variables which can be stored in
memory.
– Such variables that hold memory addresses are called
pointers.
– Since a pointer is a variable, its value is also stored in
some memory location.
Contd.
Suppose we assign the address of xyz to a variable p.
– p is said to point to the variable xyz.
…… ……
Address vs. Value
Each memory cell has an address associated with it.
Each cell also stores some value.
50 76
…… ……
Address vs. Value
Each memory cell has an address associated with it.
Each cell also stores some value.
Don‟t confuse the address referring to a memory location
with the value stored in that location.
……
50 76 ……
Values vs Locations
1024
32 Value
x
Address
Name
Pointers
A pointer is just a C variable whose value is the address
of another variable!
After declaring a pointer:
int *ptr;
ptr doesn‟t actually point to anything yet. We can either:
–make it point to something that already exists, or
– allocate room in memory for something new that it
will point to… (next time)
Pointer
int x;
int * xp ;
Pointer
int x;
Pointer to int
int * xp ;
Pointer
int x;
Pointer to int
int * xp ;
xp = &x ;
Pointer
int x;
Pointer to int
int * xp ;
xp = & x ;
Address of X
Pointer
int x;
Pointer to int
int * xp ;
1024: 32
xp = & x ;
Address of X
1024
Pointer
int x;
Pointer to int
int * xp ;
1024: 32
xp = & x ;
Address of X
1024
*xp = 0; /* Assign 0 to x */
*xp = *xp + 1; /* Add 1 to x */
Pointer
int x; Pointer to int
int * xp ;
1024: 32
xp = & x ;
Address of X
*xp = 0; /* Assign 0 to x */ 1024
*xp = *xp + 1; /* Add 1 to x */
Pointers
…..
Abstractly
(x == *p) True
int x;
(p == &x) True
int * p;
p=&x;
Pointers
Declaring a pointer just allocates space to hold the
pointer – it does not allocate something to be pointed
to!
Local variables in C are not initialized, they may
contain anything.
Pointer Usage Example
Pointer Usage Example
Pointer Usage Example
Pointer Usage Example
Pointer Usage Example
Recall
Pointer Introduction
Accessing the Address of a Variable
The address of a variable can be determined using the
„&‟ operator.
– The operator „&‟ immediately preceding a variable
returns the address of the variable.
Example:
p = &xyz;
– The address of xyz (1380) is assigned to p.
The „&‟ operator can be used only with a simple variable
or an array element.
&distance
&x[0]
&x[i-2]
Contd.
Following usages are illegal:
&235
• Pointing at constant.
&(a+b)
• Pointing at expression.
Example
#include <stdio.h> Address of A: 3221224908
main() Address of B: 3221224904
{ Address of C: 3221224900
int a; Address of D: 3221224892
float b, c; Address of ch: 3221224891
double d;
char ch;
a = 10; b = 2.5; c = 12.36; d = 12345.66; ch = „A‟;
printf (“%d is stored in location %u \n”, a, &a) ;
printf (“%f is stored in location %u \n”, b, &b) ;
printf (“%f is stored in location %u \n”, c, &c) ;
printf (“%ld is stored in location %u \n”, d, &d) ;
printf (“%c is stored in location %u \n”, ch, &ch) ;
}
Output:
10 is stored in location 3221224908
2.500000 is stored in location 3221224904
12.360000 is stored in location 3221224900
12345.660000 is stored in location 3221224892
A is stored in location 3221224891
Pointer Declarations
Pointer variables must be declared before we use them.
• General form:
data_type *pointer_name;
pointer_name Variable
(data_type) (data_type)
Contd.
Example:
int *count;
float *speed;
float x;
int *p;
: will result in erroneous output
p = &x;
int *count;
:
count = 1268;
Accessing a Variable Through its Pointer
Once a pointer has been assigned the address of a
variable, the value of the variable can be accessed
using the indirection operator (*).
int a, b;
int *p; b = a;
:
p = &a;
b = *p;
Example
#include <stdio.h>
main()
{
Equivalent
int a, b;
int c = 5;
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b);
}
Example
#include <stdio.h>
main()
{
int x, y;
int *ptr;
x = 10 ;
ptr = &x ;
y = *ptr ;
printf (“%d is stored in location %u \n”, x, &x) ;
printf (“%d is stored in location %u \n”, *&x, &x) ;
printf (“%d is stored in location %u \n”, *ptr, ptr) ;
printf (“%d is stored in location %u \n”, y, &*ptr) ;
printf (“%u is stored in location %u \n”, ptr, &ptr) ;
printf (“%d is stored in location %u \n”, y, &y) ;
*ptr = 25;
printf (“\nNow x = %d \n”, x);
}
Output:
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
10 is stored in location 3221224908
3221224908 is stored in location 3221224900
10 is stored in location 3221224904
Now x = 25
Pointer Expressions
Like other variables, pointer variables can be used in
expressions.
Output:
Number of bytes occupied by int is 4
Number of bytes occupied by float is 4
Number of bytes occupied by double is 8
Number of bytes occupied by char is 1
void main()
{ Address of i: 1220
int i = 3 ; Address of j: 1450
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}
Passing Pointers to a Function
Pointers are often passed to a function as arguments.
– Allows data items within the calling program to be
accessed by the function, altered, and then returned to
the calling program in altered form.
– Called call-by-reference (or by address or by location).
Normally, arguments are passed to a function by value.
– The data items are copied to the function.
– Changes are not reflected in the calling program.
Example: passing arguments by value
#include <stdio.h>
main()
{
int a, b;
a = 5; b = 20; Output
swap (a, b); a=5, b=20
printf (“\n a=%d, b=%d”, a, b);
}
void swap (int x, int y)
{
int t;
t = x;
x = y;
y = t;
}
Example: passing arguments by reference
#include <stdio.h>
main()
{
int a, b;
a = 5; b = 20; Output
swap (&a, &b); a=20, b=5
printf (“\n a=%d, b=%d”, a, b);
}
void swap (int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
Recall
Pointer
& operator and * operator
int *p=&a;
int *p;
P=&a;
*p=b;
Pointer Expressions
Call by Reference and Call by Value
Using a call by reference intelligently we can make a
function return more than one value at a time, which is not
possible ordinarily.
void areaperi ( int , float *, float * );
void main( )
{
int radius ;float area, perimeter ;
printf ( "\nEnter radius of a circle " ) ;
scanf ( "%d", &radius ) ;
areaperi ( radius, &area, &perimeter ) ;
printf ( "Area = %f", area ) ;
printf ( "\nPerimeter = %f", perimeter ) ;
}
void areaperi ( int r, float *a, float *p )
{
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}
Pass by value and reference
(a) If we want that the value of an actual argument should not get
changed in the function being called, pass the actual argument
by value.
(b) If we want that the value of an actual argument should get
changed in the function being called, pass the actual argument
by reference.
(c) If a function is to be made to return more than one value at a
time then return these values indirectly by using a call by
reference.
Example
a) Write a function that receives 5 integers and returns the
sum, average and standard deviation of these numbers. Call
this function from main( ) and print the results in main( ).
b) Write a function that receives marks received by a student in
3 subjects and returns the average and percentage of these
marks. Call this function from main( ) and print the results
in main( ).
Pointers and Arrays
When an array is declared,
– 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 element.
Example
Consider the declaration:
int x[5] = {1, 2, 3, 4, 5};
– Suppose that the base address of x is 2500, and each
integer requires 4 bytes.
main( )
{
char str1[ ] = "Hello" ;
char str2[10] ;
char *s = "Good Morning" ;
char *q ;
str2 = str1 ; /* error */
q = s ; /* works */
}
Arrays In Functions
An array parameter can be declared as an array or a
pointer; an array argument can be passed as a pointer.
– Can be incremented
} }
We can use const in several situations. The following code
fragment would help you to fix your ideas about const further.
0 1234 56
1 1212 33
2 1434 80
3 1312 78
We know that the expressions s[0] and s[1] would yield the addresses
of the zeroth and first one-dimensional array respectively. From
Figure these addresses turn out to be 65508 and 65512.
Now, we have been able to reach each one-dimensional array.
What remains is to be able to refer to individual elements of a
one dimensional array.
Suppose we want to refer to the element s[2][1] using pointers.
We know (from the above program) that s[2] would give the
address 65516, the address of the second one-dimensional
array. Obviously ( 65516 + 1 ) would give the address 65518.
Or ( s[2] + 1 ) would give the address 65518. And the value
at this address can be obtained by using the value at address
operator, saying *( s[2] + 1 ). But, we have already studied
while learning one-dimensional arrays that num[i] is same as
*( num + i ). Similarly, *( s[2] + 1 ) is same as, *( *( s + 2 ) + 1
).
Thus, all the following expressions refer to the same element,
s[2][1]
* ( s[2] + 1 )
*(*(s+2)+1)
/* Pointer notation to access 2-D array elements */
main( )
{
int s[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n" ) ;
for ( j = 0 ; j <= 1 ; j++ )
printf ( "%d ", *( *( s + i ) + j ) ) ;
}}
And here is the output...
1234 56
1212 33
1434 80
1312 78
char masterlist[6][10] = {
"akshay",
"parag",
"raman",
"srinivas",
"gopal",
"rajesh"
};
Dynamic Memory Allocation
Basic Idea
General format:
ptr = (type *) malloc (byte_size);
Contd.
Examples
p = (int *) malloc(100 * sizeof(int));
– A memory space equivalent to 100 times the size of
an int bytes is reserved.
– The address of the first byte of the allocated memory
is assigned to the pointer p of type int.
How?
– By using the free function.
General syntax:
free (ptr);
where ptr is a pointer to a memory block which has
been previously created using malloc.
Altering the Size of a Block
Sometimes we need to alter the size of some
previously allocated memory block.
– More memory needed.
– Memory allocated is larger than necessary.
How?
– By using the realloc function.
If the original allocation is done as:
ptr = malloc (size);
then reallocation of space may be done as:
ptr = realloc (ptr, newsize);
Realloc
good: