Successfully reported this slideshow.
Upcoming SlideShare
×

# Lec27

197 views

Published on

A keynote on Problem Solving using Computers

Published in: Education
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

### Lec27

1. 1. Pointers Next step V. Kamakoti
2. 2. Yesterday’s class • 2-D Array can be viewed as an array of row pointers each pointing to a column pointer. • It is pointer to a pointer – Double pointer
3. 3. An example #include <stdio.h> main() { int **a, I, nrows,ncols; scanf(“%d %d”,&nrows,&ncols); a = (int *) malloc(nrows*sizeof(int *)); for (I = 0; I < nrows; I++) a[I] = (int *)malloc(ncols*sizeof(int)); } //Creates a matrix a[nrows][ncols]
4. 4. An example #include <stdio.h> main() { int **a, I, nrows,ncols; scanf(“%d %d”,&nrows,&ncols); a = (int *) malloc(nrows*sizeof(int *)); for (I = 0; I < nrows; I++) //a[I] = (int *)malloc(ncols*sizeof(int)); *(a+I) = (int *)malloc(ncols*sizeof(int)); } //Creates a matrix a[nrows][ncols]
5. 5. An example #include <stdio.h> main() { int **a, I, nrows,ncols; scanf(“%d %d”,&nrows,&ncols); a = (int *) malloc(nrows*sizeof(int *)); for (I = 0; I < nrows; I++) *(a+I) = (int *)malloc(ncols*sizeof(int)); a[2][5] = 15; printf(“%dn”,a[2][5]); } //Creates a matrix a[nrows][ncols]
6. 6. An example #include <stdio.h> main() { int **a, I, nrows,ncols; scanf(“%d %d”,&nrows,&ncols); a = (int *) malloc(nrows*sizeof(int *)); for (I = 0; I < nrows; I++) *(a+I) = (int *)malloc(ncols*sizeof(int)); a[2][5] = 15; printf(“%dn”,*(*(a+2)+5)); } //Creates a matrix a[nrows][ncols]
7. 7. An example #include <stdio.h> main() { int **a, I, nrows,ncols; scanf(“%d %d”,&nrows,&ncols); a = (int *) malloc(nrows*sizeof(int *)); for (I = 0; I < nrows; I++) *(a+I) = (int *)malloc(ncols*sizeof(int)); a[2][5] = 15; // printf(“%dn”,*(*(a+2)+5)); printf(“%dn”,*(a[2] + 5)); } //Creates a matrix a[nrows][ncols]
8. 8. What happens when we print • In Unsigned hex – “a” : 0x8049660 – “a+1”: 0x8049664 – “a+2”:0x8049668 – “*a”:134518448 == “a[0] or *(a)” – “*(a+1)”: 134527456 //ncols = 2251 – Difference is 2252, but need not be always – I worked in a system without any other user
9. 9. Reallocate #include <stdio.h> main() { int **a, I, nrows,ncols; scanf(“%d %d”,&nrows,&ncols); a = (int *) malloc(nrows*sizeof(int *)); for (I = 0; I < nrows; I++) *(a+I) = (int *)malloc(ncols*sizeof(int)); *(a+1)=(int*)malloc(ncols*sizeof(int)); printf(“%dn”,a[1] - a[0]); //It will not be 2252 free(a); } //Creates a matrix a[nrows][ncols]
10. 10. Strings • • • • • • Can be declared as matrix of characters How? Automatic initialization char *color[2] = {“red”,”black”}; This creates an array of two pointers Each of this points to a pointer to array of characters of length 4 and 6 resp.