You are on page 1of 12

Pointers (Continued ..

27/03/06

Arrays and pointers

int b[10]; b[3] = 5; this is indeed *(b+3) = 5; (b+3) is same as (3+b) So, equivalently we can write 3[b] = 5;

Advise : Try to avoid such tricky ways.

27/03/06

Array of pointers

char *val[4]; Note, [ ] has higher precedence than * it says val is an array of 4 elements. Each element is of type char * That is each element is a pointer to a char

27/03/06

Array of pointers

char *val[4]; char name1[ ] = Ram; char name2[ ] = Peter; char name3[ ] = Johnson; val[0] = name1; val[1] = name2; val[2] = val[3] = name3;

27/03/06

Array of pointers

But the following is an error. char *val[4]; scanf(%s, val[0]); But, I can do like below char *val[4]; char buf[64]; val[0] = buf; scanf(%s, val[0]);
5

27/03/06

Array of pointers

Following is correct char *week[ ] = {sun, mon, tue, wed, thu, fri, sat}; week is an array with 7 elements. Each element is of type char * week[0] is a pointer to the string constant sun , ., week[6] is a pointer to the string constant sat .
6

27/03/06

String constants Vs character arrays

Often there are many confusions with string constants and character arrays.

char a[ ] = Hello; /* This is equivalent to char a[ ] = { H, e, l, l, o, \0 }; */ a[0] = B; /* OK */ char *p = Hello; p[0] = B; /* error */
7

27/03/06

String constants Vs character arrays

char *p[ ] = { one, two, three}; char a[ ][10] = { one, two, three}; p[0][0] = b; /*error */ a[0][0] = b; /* OK */ Note the space consumed by them are also different.

27/03/06

2-dimensional arrays

int a[4][6]; This is a 2 dim. Array having 4 rows and 6 columns. Each element is an integer. It is indeed a 1 dimensional array. An array of 4 rows ! Each row is a one dimensional array having 6 ints.
a[0] a[1] a[2] a[3] *(a + 0 ) *(a + 1 ) *(a + 2 ) *(a + 3 )

Row 0 Row 1 Row 2 Row 3

27/03/06

2-dimensional arrays

int a[4][6]; a[2][3] = 10; /* this is equivalent to *(*(a + 2) + 3) = 10; */ pointers to 2 dimensional arrays is a slightly complicated issue, discussion of these are postponed.

27/03/06

10

Arrays and pointers


1 2 3
( p + 1)

int a[4] = {1,2,3,4}; int *p; p = a; (p+1)[2] = 10; /* this is same as a[3] = 10; */ /* remember a[3] is same as *(a+3) , hence (p+1)[2] = *(p+1+2) = *(a+3) = a[3] */
11

27/03/06

Pointers

Pointers is a complicated issue of C language. There are pointers to functions. How to work with pointers for multi-dimensional arrays is a a tricky one. Pointers to pointers can be a confusing one. These advanced things and are not dealt in this first level course. We can touch upon some of these things, as of the need, when we discuss about structures, files, etc.

27/03/06

12

You might also like