Dav*_*ave 3 c arrays pointers multidimensional-array
我搞砸了这个,但我真的不明白.
这是我想要做的:将一个2D char数组作为函数的输入,更改其中的值,然后返回另一个2D char数组.
而已.相当简单的想法,但想法不能在C中轻松工作.
任何想让我以最简单的形式开始的想法都值得赞赏.谢谢.
C不会从函数返回数组.
你可以做几件可能足够接近的事情:
您可以打包在阵列struct和return那个.ç 将返回struct从功能就好秒.缺点是这可能会有很多内存来回复制:
struct arr {
int arr[50][50];
}
struct arr function(struct arr a) {
struct arr result;
/* operate on a.arr[i][j]
storing into result.arr[i][j] */
return result;
}
Run Code Online (Sandbox Code Playgroud)您可以返回指向数组的指针.该指针必须指向您malloc(3)为数组分配的内存.(或者另一个不从堆栈分配内存的内存分配原语.)
int **function(int param[][50]) {
int arr[][50] = malloc(50 * 50 * sizeof int);
/* store into arr[i][j] */
return arr;
}
Run Code Online (Sandbox Code Playgroud)您可以对传递给函数的数组指针进行操作,并修改输入数组.
void function(int param[][50]) {
/* operate on param[i][j] directly -- destroys input */
}
Run Code Online (Sandbox Code Playgroud)您可以将参数用作"输出变量",并使用它来"返回"新数组.如果您希望调用者分配内存或者您想要指示成功或失败,那么这是最好的:
int output[][50];
int function(int param[][50], int &output[][50]) {
output = malloc(50 * 50 * sizeof int);
/* write into output[i][j] */
return success_or_failure;
}
Run Code Online (Sandbox Code Playgroud)
或者,为调用者分配:
int output[50][50];
void function(int param[][50], int output[][50]) {
/* write into output[i][j] */
}
Run Code Online (Sandbox Code Playgroud)您无法从函数返回数组.
你有几个选择:
struct wraparray {
int array[42][42];
};
struct wraparray foobar(void) {
struct wraparray ret = {0};
return ret;
}
int foobar(int *dst, size_t rows, size_t cols, const int *src) {
size_t len = rows * cols;
while (len--) {
*dst++ = 42 + *src++;
}
return 0; /* ok */
}
// example usage
int x[42][42];
int y[42][42];
foobar(x[0], 42, 42, y[0]);
int foobar(int *arr, size_t rows, size_t cols) {
size_t len = rows * cols;
while (len--) *arr++ = 0;
return 0; /* ok */
}