pds week 9
pds week 9
pds week 9
Pointers
Part 1
Introduction
Example
• Consider the statement
int xyz = 50;
– This statement instructs the compiler to allocate a location
for the integer variable xyz, and put the value 50 in that
location.
– Suppose that the address location chosen is 1380.
Example
Remember
xyz 1380 50 content
scanf(“%d”,&xyz);
xyz=50;
Variable name Memory address
printf(“%d”,xyz);
(identity to the (identity to the
programmer) system)
Access Protocol
1. During execution of the program, the system always associates
the name xyz with the address 1380
Pointers
– Variables that hold memory addresses are called
pointers.
– Since a pointer is a variable, its value is also stored
in some memory location.
Example
#include <stdio.h>
int main()
{
char a='A'; Returns no. of bytes required
int b=100; for data type representation
long int c=100;
float d=100.0;
double e=100.0;
return 0;
}
Example Output
a: size is 1, address is a11e251f and content is A
b: size is 4, address is a11e2518 and content is 100
c: size is 8, address is a11e2510 and content is 100
d: size is 4, address is a11e250c and content is 100.000000
e: size is 8, address is a11e2500 and content is 100.000000
Higher Address
a11e251f
• Example:
int xyz;
Declaration of pointer
Summary
• int xyz;
• int *p; int *p;
• p=&xyz; Data Type Pointer Variable
Data Type
• Pointer must have a data type. That is the data
type of the variable whose address will be stored.
– int xyz, *p; // p is the pointer to data of type int.
– float abc, *p1; // p1 is the pointer to data of type float.
– long int pqr, *p2; // p2 is the pointer to data of type long int.
NOTE
Example
#include <stdio.h>
int main()
{
int a, b;
int c = 5; Equivalent
int *p;
a = 4 * (c + 5) ;
p = &c;
b = 4 * (*p + 5) ;
printf (“a=%d b=%d \n”, a, b);
return 0;
}
Example
#include <stdio.h>
int main()
{ *&xx
int x, y;
int *ptr;
ptr=&x;
x = 10 ; &x&*ptr
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);
return 0;
}
Example Output
Output: Address of x: 3599592540
Address of y: 3599592536
10 is stored in location 3599592540 Address of ptr: 3599592528
10 is stored in location 3599592540
10 is stored in location 3599592540
10 is stored in location 3599592540
3599592540 is stored in location 3599592528
10 is stored in location 3599592536
Now x = 25
Dereferencing Pointers
• Dereferencing is an operation performed to access and
manipulate data contained in the memory location.
Example
#include<stdio.h>
int main()
{
int *iptr, var1, var2;
iptr=&var1;
*iptr=25;
*iptr += 10;
printf(“variable var1 contains %d\n”,var1);
var2=*iptr;
printf(“variable var2 contains %d\n”,var2);
iptr=&var2;
*iptr += 20;
printff(“variable var2 now has %d\n”,var2);
return 0;
}
Example
variable var1 contains 35
variable var2 contains 35
variable var2 now has 55
Typecasting
Typecasting
• void pointers
– Pointers defined to be of specific data type cannot hold
the address of another type of variable.
Example
#include<stdio.h>
int main() Output
{
First p points to a float variable and access pi=3.14128
float pi=3.14128;
Then p points to an integer variable and access num=100
int num=100;
void *p;
p=π
printf(“First p points to a float variable and access pi=%.5f\n",
*((float *)p));
p=#
printf("Then p points to an integer variable and access num=%d\n",
*((int *)p));
return 0;
}
Pointers to Pointers
• Pointer is a type of data in C
– hence we can also have pointers to pointers
• General format:
– <data_type> **<ptr_to_ptr>;
<ptr_to_ptr> is a pointer to a pointer pointing to a data object
of the type <data_type>
Example
#include<stdio.h>
int main()
{ Output
int *iptr;
int **ptriptr; variable 'data' contains 100
int data; variable 'data' contains 200
iptr=&data; variable 'data' contains 300
ptriptr=&iptr;
*iptr=100;
printf("variable 'data' contains %d\n",data);
**ptriptr=200;
printf("variable 'data' contains %d\n",data);
data=300;
printf("variable 'data' contains %d\n",**ptriptr);
return 0;
}
Output:
*p=10, p=24b3f6ac
*p=4195592, p=24b3f698
a=10, address(a)=24b3f6ac
Subtraction of Pointers
#include<stdio.h>
main()
{
int *p, *q;
float *f, *g;
q=p+1;
g=f+1;
printf("%d\n",(int *)q-(int *)p);
printf("%d\n",(float *)g-(float *)f);
}
When two pointers are subtracted, the results are of type size_t
Both the printf statement outputs 1.
Even though the numerical values of the pointers differ by 4 in case
of integers/float, this difference is divided by the size of the type
being pointed to.
• After the assignment p = &A[i]; the increment p++ (or ++p) lets p one
element down the array, whereas the decrement p-- (or --p) lets p
move by one element up the array. (Here "up" means one index less,
and "down" means one index more.)
• As you may jump ahead of the position with the largest legal index,
you are also allowed to jump before the opening index (0).
Example
• Consider the declaration:
int *p;
int x[5] = {1, 2, 3, 4, 5} ;
– Suppose that the base address of x is 2500, and each
integer requires 4 bytes.
Element Value Address
x[0] 1 2500
x[1] 2 2504
x[2] 3 2508
x[3] 4 2512
x[4] 5 2516
– Relationship between p and x:
p = &x[0] = 2500
p+1 = &x[1] = 2504
p+2 = &x[2] = 2508
p+3 = &x[3] = 2512
p+4 = &x[4] = 2516
Output
#include<stdio.h>
iarray[0] (f4c709d0): 1
int main()
iarray[1] (f4c709d4): 2
{ iarray[2] (f4c709d8): 3
int iarray[5]={1,2,3,4,5}; iarray[3] (f4c709dc): 4
int i, *ptr; iarray[4] (f4c709e0): 5
ptr=iarray;
for(i=0;i<5;i++) {
printf(“iarray[%d] (%x): %d\n",i,ptr,*ptr);
ptr++;
}
return 0;
}
More examples
Output
#include<stdio.h>
11111
int main()
22222
{ 33333
int i; 44444
int a[5]={1,2,3,4,5}, *p = a; 55555
for(i=0;i<5;i++,p++) {
printf("%d %d",a[i],*(a+i));
printf(" %d %d %d\n",*(i+a),i[a],*p);
}
return 0;
}
scanf Revisited
int x, y ;
printf (“%d %d %d”, x, y, x+y) ;
2. Put smallest in x
• Swap x, y if necessary; then swap x, z if necessary.
Hints
#include <stdio.h>
int main()
{
int x, y, z ;
………..
scanf(“%d %d %d”, &x, &y, &z) ;
if (x > y) swap (&x, &y);
if (x > z) swap (&x, &z);
if (y > z) swap (&y, &z) ;
………..
}
• Rules:
– The array name must appear by itself as argument, without brackets
or subscripts.
– The corresponding formal argument is written in the same manner.
• Declared by writing the array name with a pair of empty brackets.
• Dimension or required number of elements to be passed as
a separate parameter.
int *array
float avg (int array[ ],int size)
{
#include <stdio.h> int *p, i , sum = 0;
int main()
{ p = array ; p[i]
int x[100], k, n ;
scanf (“%d”, &n) ; for (i=0; i<size; i++)
for (k=0; k<n; k++) sum = sum + *(p+i);
scanf (“%d”, &x[k]) ;
printf (“\nAverage is %f”, avg (x, n)); return ((float) sum / size);
return 0; }
}
Structures Revisited
• Recall that a structure can be declared as:
struct stud {
int roll;
char dept_code[25];
float cgpa;
};
struct stud a, b, c;
Arrays of Structures
• We can define an array of structure records as
struct stud class[100] ;
class[i].roll
class[20].dept_code
class[k++].cgpa
• The assignment
ptr = class ;
will assign the address of class[0] to ptr.
Example
#include <stdio.h>
A Warning
• When using structure pointers, we should take care
of operator precedence.
– Member operator “.” has higher precedence than “*”.
• ptr –> roll and (*ptr).roll mean the same thing.
• *ptr.roll will lead to error.
void main()
{
struct complex a, b, c;
scanf (“%f %f”, &a.re, &a.im);
scanf (“%f %f”, &b.re, &b.im);
c = add (a, b) ;
printf (“\n %f %f”, c.re, c.im);
}
Basic Idea
Basic Idea
• C language requires the number of elements in an
array to be specified at compile time.
– Often leads to wastage or memory space or program
failure.
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
• free
Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
malloc()
• A block of memory can be allocated using the
function malloc.
– Reserves a block of memory of specified size and
returns a pointer of type void.
– The return pointer can be assigned to any pointer
type.
• General format:
ptr = (type *) malloc (byte_size) ;
malloc()
• 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.
p
malloc()
Point to Note
• malloc always allocates a block of contiguous
bytes.
#include <stdio.h>
#include <stdlib.h> Example: malloc()
void main()
{
int i,N;
float *height;
float sum=0,avg;
for(i=0;i<N;i++)
sum+=height[i];
avg=sum/(float) N;
calloc()
The C library function
– void *calloc(size_t nitems, size_t size)
allocates the requested memory and returns a
pointer to it.
calloc() or malloc()
• malloc() takes a single argument (memory required
in bytes), while calloc() needs two arguments.
int main ()
Output {
int i,n;
Amount of numbers to be entered: 5 int * pData;
Enter number #1: 23
Enter number #2: 31 printf ("Amount of numbers to be entered: ");
Enter number #3: 23 scanf ("%d",&i);
Enter number #4: 45
Enter number #5: 32 pData = (int*) calloc (i,sizeof(int));
You have entered: 23 31 23 45 32 if (pData==NULL) exit (1);
for (n=0;n<i;n++) {
printf ("Enter number #%d: ",n+1);
scanf ("%d",&pData[n]);
}
printf ("You have entered: ");
for (n=0;n<i;n++)
printf ("%d ",pData[n]);
free (pData);
return 0;
}
• How?
– By using the free() function.
• General format:
free (ptr) ;
where ptr is a pointer to a memory block which has been
already created using malloc() / calloc() / realloc().
• How?
– By using the realloc() function.
#include <stdio.h>
#include <stdlib.h>
Example: realloc()
int main(void) Output
{
int *pa, *pb, n; 40 bytes allocated. Storing ints: 0 1 2 3 4 5 6 7 8 9
/* allocate an array of 10 int */ 4000000 bytes allocated, first 10 ints are: 0 1 2 3 4 5 6 7 8 9
pa = (int *)malloc(10 * sizeof *pa);
if(pa) {
printf("%zu bytes allocated. Storing ints: ", 10*sizeof(int));
for(n = 0; n < 10; ++n)
printf("%d ", pa[n] = n);
}