Wednesday 13 February 2013

Two Dimensional Arrays and Pointers in C Programming language



Extending the logic of declaring one-dimensional character arrays, we can also declare two-d charater arrays.

char *things[6];

Individual strings can be initialised by separate assignment statements since each element of this array is a pointer.

things[0] = "Raindrops on roses";
things[1] = "And Whiskers on kittens";
things[2] = "Bright copper kettles";
things[3] = "And Warm woollen mittens";
things[4] = "Brown paper packages tied up with strings";
things[6] = "These are a few of my favourite things";

The third line of the song can be printed by the following statement:

printf("%s", things[2]);

Now, let us complicate things a little further and apply pointer arithmetic to two-d arrays.

Consider the following declaration:

int num[3][4] = {
{3,6,9,12},
{15,25,30,35},
{66,77,88,99},
};

This statements actually declares an array of 3 pointers (constant) num[0], num[1], num[2] each containing the address of the first element of three single dimensional arrays.

0 comments:

Post a Comment

Powered by Blogger.