Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Esc101: Fundamentals of Computing Esc101: Fundamentals of Computing
Announcements
Last date for course drop is 20th October.
I will sign drop requests till 17th October.
Lec-22
Recap
Pointer Operations p Passing arrays as pointers Passing pointers as arrays Sizeof
Lec-22
{ printf (%d\t, *p); p++; i++; } printf (\n); } int main ( ) { int a [ ] = {3, -2, 7, 19}; print_array (a, 4); read_array ( , 4); y (a, ); print_array (a, 4); }
{ printf (%d\t, a[i]); i++; } printf (\n); } int main ( ) { int b [ ] = {3, -2, 7, 19}; int *p = b; p print_p pointer (p, 4); ); print_pointer (p+1, 3); read_pointer (p, 4); print_pointer (p, 4); }
4
Lec-22
Lec-22
Lec-22
void f (const int * p) { int j; *p = 0; // Wrong p = &j; // Permitted } void g (int * const p) { int j; *p = 0; // Permitted p = &j; // Wrong }
Lec-22
Void Pointers
Useful as a generic pointer type We can use type casting to cast into any type of pointer. One can write functions in a way that different types of arguments can be given to the function as arguments. A pointer to char, float, int, etc., can match as argument against a void pointer type.
Lec-22
10
Void Pointers
void generic (void *a, int b) { if (b == 1) { printf (Received Integer Pointer\n); printf (%d\n, * (int *) a); } else if (b == 2) { printf (Received Character Pointer\n); printf (%c\n, * (char *) a); } else if (b == 3) { printf (Received Floating Point Pointer\n); printf (%f\n, * (float *) a); } }
Lec-22 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 11
Void Pointers
#include <stdio.h> // Code for generic (void *a, int b) will come here int main ( ) { int i = 15; char c = y; float f = 15.5; ; generic (&i, 1); generic (&c, 2); generic (&f, 3); }
Lec-22 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 12
Generic Exchange
void genericexchange (void *a, void *b, int c) { if (c == 1) { int temp = * (int *) a; ( ) ( ) * (int *) a = * (int *) b; * (int *) b = temp; } else if (c == 2) { char temp = * (char *) a; * (char *) a = * (char *) b; * (char *) b = temp; } else if (c == 3) { float temp = * (float *) a; p ( ) ; * (float *) a = * (float *) b; * (float *) b = temp; } }
Lec-22 Dheeraj Sanghi, CSE Dept., IIT Kanpur ESc101, 2011-12-Monsoon 13
Any Questions?
Lec-22
14