【发布时间】:2020-11-15 15:53:01
【问题描述】:
我正忙于一项任务,但我不知道如何解决问题。作为程序的一部分,我需要编写一个添加函数。该计划的目标是:
-
从命令行读取两个整数值 n1 和 n2。
-
分配两个整数数组array1和array2,大小分别为n1和n2
-
用值 0,1....,n1-1 和 0,1....,n2-1 初始化两个数组
-
写一个带有签名的add函数:
void add(... array1, ... n1, ... array2, ... n2, ... array3, ... n3)
该函数应提供以下功能:
- 分配一个整数数组array3,大小为n3 = max(n1,n2);
- 将array1和array2这两个数组逐个元素添加到array3中;
- 仅添加第一个 min(n1,n2) 元素,并在两个数组的长度不同时复制较长数组中的元素;
- 分别通过第五个和第六个函数参数返回array3 及其长度n3。不要更改 add 函数的签名。
我卡在 add 函数的部分。我看不到 array3 必须是输入参数,但也需要在函数中分配。同样的困惑也适用于 n3。
我得到的提示是我需要使用双指针。
问题:如何实现函数的第一个功能点,同时保持函数签名不变?
提前非常感谢 :) 纳丁
编辑:
到目前为止我的代码:
// Include header file for standard input/output stream library
#include <iostream>
// Your implementation of the add functions starts here...
void add(int *array1, int *array2, int **array3){
array1[5] = 20;
}
// The global main function that is the designated start of the program
int main(int argc,char* argv[]){
// Read integer values n1 and n2 from the command line
//int n1;
//int n2;
//n1 = atoi(argv[1]);
//n2 = atoi(argv[2]);
// Allocate and initialize integer arrays array1 and array2
int n1 = 10;
int n2 = 10;
int* array1 = NULL;
array1 = new int[n1];
int* array2 = NULL;
array2 = new int[n2];
for (int x = 0; x<n1; x++)
{
array1[x] = x;
}
for (int y = 0; y<n2; y++)
{
array2[y] = y;
}
int *array3;
// Test your add function
add(array1, array2, &array3);
delete[] array1;
delete[] array2;
delete[] array3;
// Return code 0 to the operating system (= no error)
return 0;
}
【问题讨论】:
-
我的建议是把问题分解成你能理解的部分。
-
分配动态数组的首选
c++方式是使用std::vector -
虽然它不是学校介绍课程的首选类型.. @drescherjm
-
教学无能。而不是教
c++仍然教 c 的课程应该在 2 多年前被放弃。 -
当对作业的要求感到困惑时,与给你的人交谈。只需与您的老师交谈。没有必要去网上找陌生人,希望他们能猜出你老师想要什么。
标签: c++