作为我们计算机科学类(class)(使用 C)的一部分,我们将使用指针构建一个非常浪费的系统 由于此时不允许使用结构,因此我们只能对动态数组使用指针。
我已经创建了动态数组 **students 并为其分配了空间。 此时,我将这个动态数组(**students)发送到一个函数,该函数将其发送到另一个函数(我发送 &students,以便我可以通过地址更改它们)
我的问题是,我不知道(显然 - 经过多次尝试)如何为这个动态数组重新分配空间
具体来说,因为我发送了数组两次: 我的第一个函数接收***学生 我的第二个函数接收 ****students
我尝试通过以下方式重新分配空间(我目前处于第二个功能中)
*students = (char**)realloc(*students, 2 * sizeof(char*));
*students[1] = (char*)malloc(sizeof(char))
这似乎是这样做的方法 - 显然我错了 如有任何帮助,我们将不胜感激:)
编辑:
如果我这样做,程序就会运行:
**students = (char**)realloc(**students, 2 * sizeof(char*));
但是我无法正确使用 malloc..
我希望您能理解我的问题,而不仅仅是解决方案,这样我就可以为下一次试验学习。
最佳答案
I have created the dynamic-array **students and allocated space for it. at this point, i send this dynamic array (**students) to a function that sends it to ANOTHER function (i send &students so i can change them by address) … To be specific, since i sent the array 2 times: my first function receives ***students and my second function receives ****students
多次获取数组指针的地址(即&students
)是没有意义的,因为我们已经有了重新分配数组的方法:
void ANOTHER_function(char ***students)
{
*students = realloc(*students, 2 * sizeof **students); // room for 2 char *
(*students)[1] = malloc(sizeof *(*students)[1]); // room for 1 char
}
void a_function(char ***students)
{
ANOTHER_function(students); // no need for address operator & here
}
int main()
{
char **students = malloc(sizeof *students); // room for 1 char *
students[0] = malloc(sizeof *students[0]); // room for 1 char
a_function(&students);
}
因此,我们在此处不需要超过三个 *
。
当你有 ANOTHER_function(char ****students)
时
*students = (char**)realloc(*students, 2 * sizeof(char*));
*students
的类型是 char ***
,与右侧的 (char**)
不匹配 - 幸运的是,因为 *students
是 main
的 students
的地址而不是它的值。
**students = (char**)realloc(**students, 2 * sizeof(char*));
在这种情况下是正确的(尽管过于复杂);新元素对应的 malloc()
为
(**students)[1] = malloc(sizeof *(**students)[1]);
关于c - 重新分配指针的指针的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34312891/