Tuesday, January 22, 2008

2D arrays - Pointer to Array - Array of Pointers - pointer to pointer

This article focuses on 2D arrays and use of pointers to access them.

Simple Declaration:

int arr[2][3];
This way we are declaring a 2X3 array or matrix
arr[0][0] arr[0][1] arr[0][2]
arr[1][0] arr[1][1] arr[1][2]

This type of declaration is useful when we know the size of array.
Useful in embedded programming, where, standards guide that fixed arrays have to be used as RAM size is limited.

int arr[2][3] = {1,2,3,4,5,6};
This way we are declaring a 2X3 array or matrix
1 2 3
4 5 6


USING POINTERS


- Pointer to 3 integer array

int (*arr) [3];

This means that you are declaring and array which points to 3 integers.

arr will point to these 3 integers [i1][i2][i3] - Note these we can all as COLUMNS
So, number of columns to this 2D array are now fixed to 3

However, at this time there is no memory allocated to this arr
(i.e arr is not having any valid location in RAM)

To provide that with some location, we need to use malloc function

Suppose, we want to add 4 rows, then we will have to write the following:

*arr = (int *) malloc(4 * 3 * sizeof(int));

or

(int (*) [3]) arr = (int (*) [3]) malloc (2 * 3 * sizeof(int));

Note, we need to typecast the return type as (int *) that is pointer to the integer. It is to avoid arr from receiving a (char *) which is the default typecast.

so, malloc will allocate 2 *3 integer type memory to this variable and return the address of the first integer.

we can the fill the array by accessing individual elements:

*(*(arr + 0)+0) = 0;
*(*(arr + 0)+1) = 1;
*(*(arr + 0)+2) = 2;

*(*(arr + 1)+0) = 3;
*(*(arr + 1)+1) = 4
*(*(arr + 1)+2) = 5;

close watch:

*(arr+x) here x corresponds to the row number. As we have arr declared as pointer to 3 integers, we need to first access 0th row and then access 0th column.
*(*(arr+x)+y) here y represents the column number.


Array of Pointers

int *arr[2];

This will create 2 array of pointers or we can say rows

arr[0]
arr[1]

Hence the number of rows are fixed and columns can be dynamically created.

Note here that we need to allocate memory for individual pointer.


arr[0] = (int *) malloc(3 * sizeof(int));
arr[1] = (int *) malloc(3 * sizeof(int));

now, each of the rows has been allocated with 3 columns.

we can fill individual elements

*(a[0] + 0) = 0;
*(a[0] + 1) = 1;
*(a[0] + 2) = 2;


*(a[1] + 0) = 3;
*(a[1] + 1) = 4;
*(a[1] + 2) = 5;

-> point to note here is we can represent
a[0] as *(a+0)
a[1] as *(a+1)


POINTER 2 POINTER

To be filled

No comments: