Examples of Pointers and Multi-Dimensional Arrays 1
For Complete YouTube Video: Click Here
In this class, we will try to understand Examples of Pointers and Multi-Dimensional Arrays 1.
We have already discussed the concepts of Pointers and Multi-dimensional arrays.
The concepts we discuss in this class are essential to understand as they were frequently asked in campus placements and GATE examinations.
Table of Contents
Examples of Pointers and Multi-Dimensional Arrays 1
Example
The image below is an example of Pointers and Multi-Dimensional Arrays.
In our discussion on multi-dimensional arrays, we understood that multi-dimensional arrays are “Array of Arrays.”
In the above example, we have a two-dimensional array of three rows and four columns.
We can visualize the above array concerning the definition is as shown below.
The outline marked in red is an array of arrays in green color.
The printf in the example has two ways to display an element of an array.
- The first method is the conventional method of accessing the elements of an array using square brackets. “a[1][2]” which is 6.
- The second method is by using the pointer or array arithmetic. *(*(a + 1) + 2).
First Method
In the first method, we can access an array element by the row-major or column-major order.
Second Method
In the second method, we can access an array element by pointer or array arithmetic.
The expression for the pointer or array arithmetic method is *(*(a + 1) + 2).
We try to understand the expression evaluation step-by-step.
First, the expression a + 1 is evaluated.
In a one-dimensional array, adding an integer to the ‘array’ will move to the starting address of the next element in an array.
Adding an integer to an ‘array’ will move to the next row in a two-dimensional array.
The image below shows the effect of a + 1.
In our case, a + 1 means address location 116.
Next, *(a + 1) will be evaluted.
The indirect operator will get the value stored in that location.
In our case, it is the address of the first element, which is 116, as shown in the image below.
Now, *(a + 1) + 2 will get evaluated, means 2 will be added to 116.
Adding 2 to an address means crossing two elements, which is 124, as shown in the image below.
Now, *(124) is getting the value stored in 124 memory locations, 6 as shown in the image below.