Linux Systems Programming: Inter Process Communication (IPC) using Pipes
13. Pointer and 2D array
1.
2. In a two dimensional array, we can access each
element by using two subscripts.
first subscript represents the row number and
second subscript represents the column number
second subscript represents the column number
Consider the following declaration statement,
3. The above declaration statement creates a 3x4
matrix initialized with the following values:
4. The element at ith row, jth column can be
accessed using
a[i][j].
To access the value 7, we have to use
a[1][2].
a[1][2].
5. Let us see how pointer is used to access the 2-D
array.
As we know, name of the array gives the base
address of the array i.e., address of a[0][0].
To access a[i][j] using base pointer of the array,
To access a[i][j] using base pointer of the array,
we can use the following generalized form:
6. The following figure shows how the above 2-D array
will be stored in memory.
Array elements are stored in memory row by row.
7. In a 2-D array, each row will be considered as a one
dimensional array.
Hence 2-D array can be considered as a collection of several
one dimensional arrays.
In this example, each row is an array of 4 integers.
We know that the name of an array is a constant pointer that
points to 0th row which contains address 1000.
points to 0th row which contains address 1000.
8.
9. Consider a two dimensional array mat[ROWS] [COLS]
where ROWS and COLS are some integer value.
We can use any one of the following two notations to
access the two dimensional array.
The first int mat[][COLS] is general array notation.
Whereas int (*mat)[COLS] is a pointer to array.
10.
11. For passing multidimensional arrays,
First array dimension does not have to be
specified.
The second dimension must be explicitly
The second dimension must be explicitly
specified or a pointer to pointer as a parameter
to receive the address.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28. Returning a 2D array from function is not as straight as passing
an array to a function.
Arrays in C are passed by reference, hence any changes made to
array passed as argument persists after the function.
So you can accept the output array you need to return, as a
parameter to the function.
parameter to the function.
The following program demonstrates how a 2-D array is returned
from a function by passing resultant array also as a parameter.
In the following program, main() receives two matrices as input
and these two matrices along with resultant matrix are passed as
arguments to the function sum().
The sum() function adds the two matrices and return the
resultant matrix as result to the main() function.