gpt4 book ai didi

将二维数组复制到另一个

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:53 24 4
gpt4 key购买 nike

我正在从“C Primer Plus”一书中学习 C 编程语言。我正在解决一个练习,但我撞墙了:

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).

我不能使用 VLA,因为我的编译器不支持它,我使用 VC2013。这是我的代码:

#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;
}

输出:http://postimg.org/image/mnswuyy2b/

我不知道如何将 size 变量的值传递给函数 copy_arr。除了VLA还有其他方式吗?

最佳答案

arr1[LIM1][LIM2] 是一个大小为 LIM1 的数组,由大小为 LIM2 的数组组成。因此copy_arr的签名应该是:

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

或者因为 C++ 允许省略第一维:

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

或者,由于数组到指针的转换,数组可以转换为指向大小为 LIM2 的数组的指针:

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

您的代码中还有另一个问题:

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

最后一个分号使以下 {} block 不属于循环。将其删除。

Online Demo

关于将二维数组复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25856413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com