How it works...

Whenever an array is defined, the memory allocated to it internally is a sequential memory. Now let's define a matrix of size 2 x 3, as shown in the following diagram. In that case, the matrix will be assigned six consecutive memory locations of two bytes each (see Figure 5.33). Why two bytes each? This is because an integer takes two bytes. This also means that if we define a matrix of the float type that takes four bytes, each allocated memory location would consist of four bytes:

Figure 5.33

In reality, the memory address is long and is in hex format; but for simplicity, we will take the memory addresses of integer type and take easy-to-remember numbers, such as 1000, as memory addresses. After memory address 1000, the next memory address is 1002 (because an integer takes two bytes).

Now, to display the original matrix elements in row-major form using a pointer, we will need to display the elements of memory locations, 1000, 1002, 1004, and so on:

Figure 5.34

Similarly, in order to display the transpose of the matrix using a pointer, we will need to display the elements of memory locations; 1000, 1006, 1002, 1008, 1004, and 1010:

Figure 5.35

Let's use GCC to compile the transposemat.c program as follows:

D:\CBook>gcc transposemat.c -o transposemat

If you get no errors or warnings, that means that the transposemat.c program has been compiled into an executable file, transposemat.exe. Let's run this executable file with the following code snippet:

D:\CBook>./transposemat
Enter rows and columns of matrix: 2 3

Enter elements of matrix:
1
2
3
4
5
6

Matrix using pointer is:
1 2 3
4 5 6

Transpose of Matrix:
1 4
2 5
3 6

Voilà! We've successfully found the transpose of a matrix using pointers. Now, let's move on to the next recipe!