POINTERS
1
26/12/22
Declaration – a point about pointers
2
26/12/22
Pointing to nothing !
3
26/12/22
<stdio.h> with 0 (zero)
*p = 5; /* this results in run-time error */
Functions
4
26/12/22
Functions – an example
5
26/12/22
void find_min_max_marks(float *, float *, float *, int); main( )
{
float min, max, marks[40];
… …;
find_min_max_marks(marks, &min, &max, 40);
}
void find_min_max_marks(float *m, float *a, float *z, int size)
{
int j;
*z = m[0]; *a = m[0]; for (j=1; j<size; j++) {
if(m[j] < *a) *a = m[j];
if(m[j] > *z) *z = m[j];
}
}
Comparing two strings
6
26/12/22
strcmp – array version
7
26/12/22
int strcmp(char *s, char *t)
{
int j;
for(j=0; s[j] == t[j]; j++)
if( s[j] == ‘\0’) return 0;
return s[j] – t[j] ;
}
strcmp – pointer version
8
26/12/22
int strcmp( char *s, char *t)
{
for ( ; *s == *t; s++, t++) if(*s == ‘\0’) return 0;
return *s - *t;
}
const with pointers
9
26/12/22
const with pointers
10
26/12/22
A non-constant pointer to non- constant data
11
26/12/22
*p = 15; /* contents pointed by p is modified */ p = &k; /* p is modified */
A constant pointer to non-constant data
12
int * const ptr = &x;
*ptr = 7; /* OK same as x = 7*/ ptr = &y; /* error */
A constant pointer to non-constant data
13
26/12
A non-constant pointer to constant data
14
A non-constant pointer to constant data
15
ptr = &j; /* OK */
*ptr = 25; /* error */ j = 25; /* OK */
ptr = &k; /* OK */
*ptr = 100; /* error */ k = 100; /* OK */
j = *ptr; /* OK */
A non-constant pointer to constant data
{
int y = 111; f(&y);
}
void f( const int * ptr)
{
*ptr = 100; /* an error occurs */
}
16
A constant pointer to constant data
17
const int *const ptr = &x;
y = *ptr; ptr = &y;
/* OK */
/* error */
*ptr = 20; /* error */
Pointer Expressions and Pointer Arithmetic
18
Increment ++ and decrement --
19
ptr = a;
ptr ++; /* ptr now points to a[1] */
*ptr = 10; /* same as a[1] = 10 */ ptr = &j;
ptr ++;
/* now ptr points to next integer after j */
Subtracting a pointer from other
20
a = &d[4];
b = &d[10];
j = b – a; /* j gets value 6 */
Assigning a pointer to another – Void pointer
21
p = (int *) c;
void pointer
22
assign*/