Session 6
Session 6
1
Introduction
2
Basic Concept
3
Contd.
xyz variable
50 value
1380 address
4
Contd.
5
Contd.
xyz 50 1380
p = &xyz;
p 1380 2545
6
Address vs. Value
7
Values vs Locations
32 value
1024:
x
address name New Type : Pointer
8
Pointers
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)
9
Pointer
11
Pointer Usage Example
0xcafe 0000
0xbeef 0000
0x0000 0004
0x0000 0000
12
Pointer Usage Example
0x0000 0004
0x0000 0000
13
Pointer Usage Example
0x0000 0004
0x0000 0000
14
Pointer Usage Example
0x0000 0004
0x0000 0000
15
Pointer Usage Example
16
Accessing the Address of a Variable
• Example:
p = &xyz;
– The address of xyz (1380) is assigned to p.
•
Following usages are illegal:
&235
• Pointing at constant.
int arr[20];
:
&arr;
• Pointing at array name.
&(a+b)
• Pointing at expression.
18
Example
#include <stdio.h>
main()
{
int a;
float b, c;
double d;
char ch;
19
Output:
20
Pointer Declarations
• General form:
data_type *pointer_name;
21
Contd.
• Example:
int *count;
float *speed;
22
Things to Remember
float x;
int *p;
: will result in erroneous output
p = &x;
int *count;
:
count = 1268;
23
Accessing a Variable Through its Pointer
int a, b;
int *p; Equivalent to b = a;
:
p = &a;
b = *p;
24
Example 1
#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);
} a=40 b=40
25
Example 2
#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);
}
26
3221224908
Address of x:
3221224904
Address of y:
3221224900
Address of ptr:
Output:
Now x = 25
27
Pointer Expressions
28
Contd.
29
Contd.
30
Scale Factor
31
Contd.
32
• Note:
– The exact scale factor may vary from one machine to another.
– Can be found out using the sizeof function.
– Syntax:
sizeof (data_type)
33
Example: to find the scale factors
#include <stdio.h>
main()
{
printf (“No. of bytes occupied by int is %d \n”, sizeof(int));
printf (“No. of bytes occupied by float is %d \n”, sizeof(float));
printf (“No. of bytes occupied by double is %d \n”, sizeof(double));
printf (“No. of bytes occupied by char is %d \n”, sizeof(char));
}
Output:
34
Passing Pointers to a Function
35
Example: passing arguments by value
#include <stdio.h>
main()
{
int a, b;
a = 5; b = 20;
swap (a, b); Output
printf (“\n a=%d, b=%d”, a, b);
} a=5, b=20
38
Example
39
Contd.
#include <stdio.h>
main() float avg (int array[], int size)
{ {
int x[100], k, n; int *p, i , sum = 0;
41
Arrays and pointers
42
Arrays
• Consequences: (int ar[10];)
–ar is a pointer
–ar[0] is the same as *ar
–ar[2] is the same as *(ar+2)
–We can use pointer arithmetic to access arrays more
conveniently.
• Declared arrays are only allocated while the scope is valid
char *foo() {
char string[32]; ...;
return string;
} is incorrect
43
Arrays
44
Arrays
• Pitfall: An array in C does not know its own length, & bounds
not checked!
–Consequence: We can accidentally access off the end of
an array.
–Consequence: We must pass the array and its size to a
procedure which is going to traverse it.
• Segmentation faults and bus errors:
–These are VERY difficult to find;
be careful!
–You’ll learn how to debug these in lab…
45
Arrays In Functions
} }
46
Arrays and pointers
47
Arrays and pointers
#define N 20
int a[N], i, *p, sum;
• p = a; is equivalent to p = &a[0];
• p is assigned 300.
• Pointer arithmetic provides an alternative to array indexing.
• p=a+1; is equivalent to p=&a[1]; (p is assigned 304)
int a[N];
• a is a constant pointer.
49
Pointer arithmetic and element size
double * p, *q ;
• The expression p+1 yields the correct machine address for the
next variable of that type.
• Other valid pointer expressions:
– p+i
– ++p
– p+=i
– p-q /* No of array elements between p and q */
50
Pointer Arithmetic
– x = (*p)++ x = *p ; *p = *p + 1;
51
Pointer Arithmetic
52
Pointer Arithmetic
53
Pointer Arithmetic
54
Example with 2-D array
TO BE DISCUSSED LATER
55
Structures Revisited
struct stud {
int roll;
char dept_code[25];
float cgpa;
};
struct stud a, b, c;
56
Arrays of Structures
57
Example :: sort by roll number (bubble sort)
58
Example :: selection sort
int min_loc (struct stud x[],
int k, int size) int selsort (struct stud x[],int n)
int j, pos; {
{ int k, m;
pos = k; for (k=0; k<n-1; k++)
for (j=k+1; j<size; j++) {
if (x[j] < x[pos]) m = min_loc(x, k, n);
pos = j; temp = a[k];
return pos; a[k] = a[m];
} a[m] = temp;
}
main() }
{
struc stud class[100];
int n;
…
selsort (class, n);
…
59
Arrays within Structures
int marks[6];
float cgpa;
};
struct stud class[100];
• You may recall that the name of an array stands for the
address of its zero-th element.
– Also true for the names of arrays of structure variables.
• Consider the declaration:
struct stud {
int roll;
char dept_code[25];
float cgpa;
} class[100], *ptr ;
61
– The name class represents the address of the zero-th
element of the structure array.
– ptr is a pointer to data objects of the type struct stud.
• The assignment
ptr = class;
will assign the address of class[0] to ptr.
62
• Once ptr points to a structure variable, the members
can be accessed as:
ptr –> roll;
ptr –> dept_code;
ptr –> cgpa;
63
A Warning
64
Structures and Functions
65
Example: complex number addition
#include <stdio.h> struct complex add (x, y)
struct complex { struct complex x, y;
float re; {
float im; struct complex t;
};
t.re = x.re + y.re ;
main() t.im = x.im + y.im ;
{ return (t) ;
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);
}
66
Example: Alternative way using pointers
#include <stdio.h>
struct complex {
float re;
float im; void add (struct complex *x,
}; struct complex *y,
struct complex *t)
{
main() t->re = x->re + y->re;
{ t->im = x->im + y->im;
struct complex a, b, c; }
scanf (“%f %f”, &a.re, &a.im);
scanf (“%f %f”, &b.re, &b.im);
add (&a, &b, &c) ;
printf (“\n %f %f”, c,re, c.im);
}
67
Dynamic Memory Allocation
68
Basic Idea
69
Contd.
70
Memory Allocation Process in C
71
Contd.
• malloc
– Allocates requested number of bytes and returns a pointer
to the first byte of the allocated space.
• 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.
73
Allocating a Block of Memory
• General format:
ptr = (type *) malloc (byte_size);
74
Contd.
• Examples
p = (int *) malloc(100 * sizeof(int));
76
Points to Note
77
Example
78
Releasing the Used Space
• 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.
79
Altering the Size of a Block
• How?
– By using the realloc function.
80
Contd.
– The new memory block may or may not begin at the same
place as the old one.
• If it does not find space, it will create it in an entirely
different region and move the contents of the old block
into the new block.
– The function guarantees that the old data remains intact.
– If it is unable to allocate, it returns NULL and the
old memory block is not freed.
81
Pointer to Pointer
• Example:
int **p;
p = (int **) malloc(3 * sizeof(int *));
p[0]
p int int *
**
p[1] int *
int *
p[2]
82
2-D Array Allocation
85
Contd.
86
Contd.
• Each structure of the list is called a node, and
consists of two fields:
– One containing the item.
– The other containing the address of the next item in the
list.
• The data items comprising a linked list need not
be contiguous in memory.
– They are ordered by logical links that are stored as part
of the data in the structure itself.
– The link is a pointer to another structure of the same
type.
87
Contd.
88
Contd.
struct node_name
{
type member1;
type member2;
………
struct node_name *next;
}
89
Illustration
90
Contd.
roll
name
age
next
n1 n2 n3
91
Example
#include <stdio.h>
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
}
main()
{
struct stud n1, n2, n3;
struct stud *p;
93
Alternative Way
94