作为我们计算机科学课程(使用C)的一部分,我们将使用指针构建一个非常浪费的系统,因为在这一点上我们不允许使用结构,我们将只对我们的动态数组使用指针。
我已经创建了dynamic-array **学生并为它分配了空间。此时,我将这个动态数组(**students)发送给一个函数,该函数再将它发送给另一个函数(我发送&students,这样我就可以通过地址来更改它们)
我的问题是,我不知道(显然,在多次尝试之后)如何将空间重新分配给这个动态数组
具体地说,因为我发送了两次数组:第一个函数接收*学生,第二个函数接收*学生
我试着用下面的方法重新分配空间(我现在在第二个函数中)
*students = (char**)realloc(*students, 2 * sizeof(char*));
*students[1] = (char*)malloc(sizeof(char))这似乎是做这件事的方法-显然我错了,任何帮助都会被感激地接受:)
编辑:
如果我这样做,程序就会运行:
**students = (char**)realloc(**students, 2 * sizeof(char*));但是我不能正确地使用malloc ..
我希望能理解我的问题,而不仅仅是一个解决方案,这样我就可以在下一次试验中学习。
发布于 2016-03-11 22:57:43
我已经创建了
-array**学生并为它分配了空间。此时,我将这个动态数组(**students)发送给一个函数,该函数再将它发送给另一个函数(我发送&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]);https://stackoverflow.com/questions/34312891
复制相似问题