1 of 12

Pointers (Continued …..)

1

2 of 12

Arrays and pointers

2

27/12/22

  • 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.

3 of 12

Array of pointers

3

27/03/22

  • 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

4 of 12

Array of pointers

4

  • char *val[4];

char name1[ ] = “Ram”; char name2[ ] = “Peter”; char name3[ ] = “Johnson”; val[0] = name1;

val[1] = name2;

val[2] = val[3] = name3;

5 of 12

Array of pointers

5

  • 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]);

6 of 12

Array of pointers

6

  • 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” .

7 of 12

String constants Vs character arrays

7

  • 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 */

8 of 12

String constants Vs character arrays

8

  • 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.

9 of 12

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.

9

Row 0

a[0]

*(a + 0 )

Row 1

a[1]

*(a + 1 )

Row 2

a[2]

*(a + 2 )

Row 3

a[3]

*(a + 3 )

10 of 12

2-dimensional arrays

10

  • 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.

11 of 12

Arrays and pointers

11

1

2

3

4

( 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] */

12 of 12

Pointers

12

  • 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.