10

Click here to load reader

Lec27

Embed Size (px)

DESCRIPTION

A keynote on Problem Solving using Computers

Citation preview

Page 1: Lec27

Pointers

Next stepV. Kamakoti

Page 2: Lec27

Yesterday’s class

• 2-D Array can be viewed as an array ofrow pointers each pointing to a columnpointer.

• It is pointer to a pointer– Double pointer

Page 3: Lec27

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]

Page 4: Lec27

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]

Page 5: Lec27

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(“%d\n”,a[2][5]);}//Creates a matrix a[nrows][ncols]

Page 6: Lec27

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(“%d\n”,*(*(a+2)+5));}//Creates a matrix a[nrows][ncols]

Page 7: Lec27

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(“%d\n”,*(*(a+2)+5)); printf(“%d\n”,*(a[2] + 5));}//Creates a matrix a[nrows][ncols]

Page 8: Lec27

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

Page 9: Lec27

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(“%d\n”,a[1] - a[0]); //It will not be 2252 free(a);}//Creates a matrix a[nrows][ncols]

Page 10: Lec27

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.