Using built in function to copy a C/C++ array is quite straight forward. However, my C language class assignment requires me to do it using one for loop only, without any built in function.

The limitation aims to make sure we apply concept of pointers, one of the most dreaded topics in C language.

First, I get started with using two for loops to copy the 2D array, and see how i can reduce the number of for loops used to one from there.

Code:

#include <stdio.h>

int main() {

  int row=3, col=3;

  int A[3][3] = { 
    {1, 2, 3},
    {3, 4, 5},
    {6, 7, 8}
  };
    
  // array B filled with zeros
  int B[3][3] = { 0 };
  
  // TWO FOR LOOPS  
  // copy array A into array B
  for (int i=0; i<row; i++) {
    for (int j=0; j<col; j++) {
        B[i][j] = A[i][j];
    }
  }

  // print array B values
  printf("Arr B = \n");
  for (int i=0; i<row; i++) {
    for (int j=0; j<col; j++) {
        printf("%d ", B[i][j]);
    }
    printf("\n");
  }
  return 0;
}

To reduce the number of for loops for copying, we will need to modify this part:

for (int i=0; i<row; i++) {
    for (int j=0; j<col; j++) {
        B[i][j] = A[i][j];
    }
}

into the following code:

// define pointers for the first element of the array
int *ptrA = &A[0][0];
int *ptrB = &B[0][0];

for (int i=0; i<9; i++) {
    printf("%d ", ptrA[i]); // 1 2 3 4 5 6 7 8 9
    ptrB[i] = ptrA[i];
}

To reduce the number of for loops used, we first define pointers that store the address of the first element of the matrix A and B. Then, we copy the value of the array by accessing the value of pointers, with syntax ptrA[i] .

The reason we can use 1 for loop only is because of the fact below:

A[0][0] = ptr[0]
A[0][1] = ptr[1]
A[0][2] = ptr[2] // go to row below
A[1][0] = ptr[3]
A[1][1] = ptr[4]
A[1][2] = ptr[5] // go to row below
A[2][0] = ptr[6]
A[2][1] = ptr[7]
A[2][2] = ptr[8]

Here, we make use of the way C language store value in memory. Starting from the first element, the pointer will go to next element when incremented by one. This means that at the last column, the pointer will go to element in the next row below.

Here is the full final version of the code:

#include <stdio.h>
#include <string.h>

int main() {
  
  int A[3][3] = { 
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
  };
  
  int B[3][3] = { 0 };

  int *ptrA = &A[0][0];
  int *ptrB = &B[0][0];
  
  for (int i=0; i<9; i++) {
    printf("%d ", ptrA[i]);// 1 2 3 4 5 6 7 8 9
    ptrB[i] = ptrA[i];
  }

  // print array B values
  printf("\nArr B = \n");

  for (int i=0; i<3; i++) {
    for (int j=0; j<3; j++) {
        printf("%d ", B[i][j]);
    }
    printf("\n");
  }

  return 0;
}

Thank you so much for reading!  😊 Feel free to follow us on twitter and like our fb page for more articles like this. 😉