Examples of Pointers and Multi-Dimensional Arrays 2

For Complete YouTube Video: Click Here

In this class, we will understand Examples of Pointers and Multi-Dimensional Arrays 2.

We have already discussed an example of Pointers and Multi-Dimensional Arrays.

We discuss more examples of Pointers and Multi-Dimensional Arrays for better understanding.

Examples of Pointers and Multi-Dimensional Arrays

Example 1

The image is Example 1 of Pointers and Multi-Dimensional Arrays.

Examples of Pointers and Multi-Dimensional Arrays 2 Ex 1
Examples of Pointers and Multi-Dimensional Arrays 2 Ex 1

In the above example, we have defined a two-dimensional array of three rows and four columns and a pointer p pointing to the ‘array.’

In the printf statement, we are trying to print the element stored in a[1][2] in two different ways.

  1. Using Array Index.
  2. Using the Pointer Arithmetic.

Based on the previous discussion, can you guess the output?

Do you think that it is going to print the value 6?

No, the compiler will generate an error.

Why?

Because p is an integer pointer, it will behave like an integer, not as a two-dimensional array.

Let’s consider the pointer arithmetic expression and understand how it will get evaluated.

The expression is *(*(p + 1) + 2).

The image below is the way the array elements will get stored in the memory and the pointer will get pointed.

Examples of Pointers and Multi-Dimensional Arrays 2 Visualization
Examples of Pointers and Multi-Dimensional Arrays 2 Visualization

First, p + 1 will get executed in the evaluation of this expression.

As the p is a pointer, integer p + 1 is just the following elements address.

*(p + 1) is 1.

Now, *(1 + 2) is not acceptable.

As * is an indirection operator, we use it to get the value stored in the memory.

The image below is the error message generated by the compiler.

Examples of Pointers and Multi-Dimensional Arrays 2 Error Message
Examples of Pointers and Multi-Dimensional Arrays 2 Error Message

Example 2

The image below is example 2.

Examples of Pointers and Multi-Dimensional Arrays 2 Ex 2
Examples of Pointers and Multi-Dimensional Arrays 2 Ex 2

In the above example, the declaration int (*p)[4] states that p is a pointer pointing to an array of four columns that stores integers.

This kind of declaration is the right way to define a pointer for two-dimensional arrays.

Now the printf statement will print 6.