Click here to load reader
Upload
sriharsha-p
View
46
Download
0
Embed Size (px)
DESCRIPTION
A keynote on Problem Solving using Computers
Citation preview
Pointers
Next stepV. Kamakoti
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
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]
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]
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]
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]
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]
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
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]
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.