Darius
Darius

Reputation: 15

Copy 2d array into another

I'm learning the C programming language from the book "C Primer Plus". I'm solving an exercise and I hit a wall:

Write a program that initializes a two-dimensional 3×5 array-of- double and uses a VLA-based function to copy it to a second two-dimensional array. Also provide a VLA-based function to display the contents of the two arrays. The two functions should be capable,in general, of processing arbitrary N×M arrays. (If you don’t have access to a VLA-capable compiler, use the traditional C approach of functions that can process an N×5 array).

I can't use VLA, as my compiler doesn't support it, I use VC2013. Here is my code:

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>

#define LIM1 10
#define LIM2 10
#define LIM3 2
int ct, ct2, size;

void copy_arr(double *[LIM3], double *[LIM3], int size, int lim);
int main(void)
{
    double arr1[LIM1][LIM2], arr2[LIM1][LIM2];

    printf("Enter the size of the array\n");
    scanf("%d", &size);
    printf("Enter the array elements\n");

    for (ct = 0; ct < size; ct++)
    {
         for (ct2 = 0; ct2 < LIM3; ct2++)
         {
             scanf("%lf", &arr1[ct][ct2]);
         }
    }
    printf("\n");

    for (ct = 0; ct < size; ct++)
    {
        for (ct2 = 0; ct2 < LIM3; ct2++)
        {
            printf("%.2f ", arr1[ct][ct2]);
        }
        printf("\n");
    }
    printf("\n");

    copy_arr(arr1, arr2, size, LIM3);

    for (ct = 0; ct < size; ++ct)
    {
        for (ct2 = 0; ct2 < LIM3; ++ct2);
        {
            arr2[ct][ct2] = arr1[ct][ct2];
            printf("%.2f ", arr2[ct][ct2]);
        }
        printf("\n");
    }
    printf("\n"); 

    system("pause");

}

void copy_arr(double (*arr1)[LIM3], double (*arr2)[LIM3], int size, int lim)
{
     for (ct = 0; ct < size; ct++)
     {
         for (ct2 = 0; ct2 < lim; ct2++)
         {
             arr2[ct][ct2] = arr1[ct][ct2];
         }
     }

return;
}

output: http://postimg.org/image/mnswuyy2b/

I can't figure out how to pass the value of the size variable to the function copy_arr. Are there other ways except VLA?

Upvotes: 0

Views: 2854

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

arr1[LIM1][LIM2] is an array of size LIM1 of arrays of size LIM2. Therefore the signature of copy_arr should be:

void copy_arr(double arr1[LIM1][LIM2], double arr2[LIM1][LIM2], int size, int lim);

or because C++ allows to omit the first dimension:

void copy_arr(double arr1[][LIM2], double arr2[][LIM2], int size, int lim);

or, because of array-to-pointer conversion, array can be converted to a pointer to array of size LIM2:

void copy_arr(double (*arr1)[LIM2], double (*arr2)[LIM2], int size, int lim);

You also have another problem in your code:

    for (ct2 = 0; ct2 < LIM3; ++ct2);

That last semicolon makes the following {} block not belong to the loop. Remove it.

Online Demo

Upvotes: 2

Related Questions