我必须创建一个复制数组并返回它的函数。
const int HEIGHT = 21;
const int WIDTH = 16;
char field [HEIGHT][WIDTH] = {
"###############",
"# #",
"# ## ### #### #",
"# ## ### #### #",
"# #",
"# ######## # #",
"# # # #",
"# # ##### # #",
"# # ##### # #",
"# # # #",
"# # # #",
"# #",
"# ## ######## #",
"# ## ######## #",
"# ## ######## #",
"# #",
"# ### ### #",
"# ########### #",
"# ########### #",
"# #",
"###############",
};
char copyArray(char copyField[][1]) { //Copy the array field to newField and return it to main
int i = 0;
int j = 0;
for (int i = 0; i < HEIGHT; i++) {
copyField[i][j] = field[i][j];
for (int j = 0; j < WIDTH; j++)
copyField[i][j] = field[i][j];
}
/* for (int i = 0; i < HEIGHT; i++) {
cout << copyField[i] << endl;
} */
return copyField[i][j];
}
int main() {
//char newField[HEIGHT][WIDTH] = copyArray();
//cout << newField[1][1] << endl;
int i = 0;
int j = 0;
char copyField[HEIGHT][WIDTH]= copyArray(*copyField[][1]);
return 0;
}
我的问题是如何将copyArray从main函数赋予copyArray函数以及如何返回它? 复制部分现在工作正常,我通过在copyArray函数中声明char copyArray [HEIGHT] [WIDTH]来测试它。 我知道向量和memcpy工作得更好,更容易,但我必须使用它。
答案 0 :(得分:0)
此示例清楚地显示了如何为函数提供数组并返回它们。
#include <stdio.h>
#include <math.h>
double* func(int i, double * mas)
{
double* mas_new = new double[i];
for(int z=0; z<i; z++)
mas_new[z] = sqrt(mas[z]);
return mas_new;
}
int main()
{
double mas[] = {1.0, 2.0, 3.0, 4.0};
double* mas_new;
for(int z=0; z<4; z++)
printf("%f ", mas[z]);
mas_new = func(4, mas);
for(int z=0; z<4; z++)
printf("%f ", mas_new[z]);
delete mas_new;
return 0;
}
有两种方法可以让数组运行。
void foo (int* arr) {
....
}
或
void foo (int arr[]) {
.....
}
建议第二个参数传递数组大小。
要从函数返回数组,您应该返回指向其第一个元素的指针。