我在此站点上阅读了有关“在 C 中传递多维数组”的示例。
这是一个使用 char 数组的好例子,我从中学到了很多。我想通过创建一个处理动态分配的一维整数数组的函数来做同样的事情,然后创建另一个处理多维整数数组的函数。我知道如何将其作为函数的返回值。但在这个应用程序中,我需要在函数的参数列表中执行此操作。
就像我上面提到的示例一样,我想将指向整数数组的指针以及元素的数量“num”(或二维数组函数的“row”和“col”等)传递给函数。 )。我在这里得到了另一个示例的重新设计版本,但我无法让它工作,尽我所能(标记来自该示例的新代码或修改的代码行)。有谁知道如何解决这个问题?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ELEMENTS 5
void make(char **array, int **arrayInt, int *array_size) {
int i;
char *t = "Hello, World!";
int s = 10; // new
array = malloc(ELEMENTS * sizeof(char *));
*arrayInt = malloc(ELEMENTS * sizeof(int *)); // new
for (i = 0; i < ELEMENTS; ++i) {
array[i] = malloc(strlen(t) + 1 * sizeof(char));
array[i] = StrDup(t);
arrayInt[i] = malloc( sizeof(int)); // new
*arrayInt[i] = i * s; // new
}
}
int main(int argc, char **argv) {
char **array;
int *arrayInt1D; // new
int size;
int i;
make(array, &arrayInt1D, &size); // mod
for (i = 0; i < size; ++i) {
printf("%s and %d\n", array[i], arrayInt1D[i]); // mod
}
return 0;
}