Write a program that initializes a two dimensional array of double and copy it to a second two dimensional array. - C Array

C examples for Array:Multidimensional Arrays

Description

Write a program that initializes a two dimensional array of double and copy it to a second two dimensional array.

Demo Code

#include <stdio.h>
#include <stdlib.h>

void copy_ptr(double *target, double *source, int arr_len);
void print_row(double (*arr)[10], int row);

int main(void){
  // copy one 10 by 10 array to another 10 by 10 array

  double source[10][10];
  double target[10][10];

  for (int i = 0; i < 10; i++)
    for (int j = 0; j < 10; j++)
      source[i][j] = rand() / (double) RAND_MAX;

  // copy source array to target
  for (int i = 0; i < 10; i++)
    copy_ptr(target[i], source[i], 10);/*from   ww w . ja va2s  .  c o  m*/

  // print arrays
  printf("%-50s", "Source");
  printf("   ");
  printf("%-50s", "Target");
  putchar('\n');

  for (int i = 0; i < 103; i++)
    putchar('-');
  putchar('\n');

  for (int i = 0; i < 10; i++){
    print_row(source, i);
    printf("   ");
    print_row(target, i);
    putchar('\n');
  }

  return 0;
}
// copy array using pointer notation
void copy_ptr(double *target, double *source, int arr_len){
  for (int i = 0; i < arr_len; i++){
    *(target + i) = *(source + i);
  }
}
// print a row from a n by 10 array of doubles
void print_row(double (*arr)[10], int row){
  for (int i = 0; i < 10; i++){
    printf("%.2f ", arr[row][i]);
  }
}

Result


Related Tutorials