Malloc没有在C中分配内存

时间:2016-04-25 08:23:22

标签: c arrays pointers

我正在尝试构建一个获取sed的函数 其中count是数组中项的数量,该组是指向数组的指针。

我必须使用(**group, *count)而不是更容易**group

修改:按要求包含我的*group功能:

main()

我不知道为什么,但int *group1, **pgroup1, count1 = 0, *pcount1; pgroup1 = &group1; printf("please enter what size do you want the array to be..\n"); scanf("%d", &count1); pcount1 = &count1; BuildGroup(pgroup1, pcount1); void BuildGroup(int** group, int* count) { int i = 0, j = 0, c = *count; group = (int**)malloc(c*sizeof(int**)); if (group == NULL) { printf("ERROR: Out of memory\n"); return 1; } printf("please enter the %d items in the array...\n", *count); for (i = 0; i < *count; i++) //going through the array items to be filled. { scanf("%d", &group[i]); for (j = 0; j < i; j++) { while (group[i] == group[j]) //checking every item if he is already in the group,if he is in the group prompting the user for re-entering. { printf("you've entered the same value as beforehand, please enter this value again..\n"); scanf("%d", &group[j]); } } } } 没有分配数组所需的内存。另一方面,它没有触发malloc所以我真的不知道我做错了什么。

1 个答案:

答案 0 :(得分:4)

看起来你传递给函数的东西(或者实际上,应该传递给函数)是指针变量的指针,然后你应该使用函数中的dereference来访问指针变量。

这样的事情:

int *group;
int count = 10;
BuildGroup(&group, &count);

这意味着你的功能看起来像

void  BuildGroup(int **group, int *count)
{
    if ((*group = malloc(*count * sizeof(**group))) == NULL)
    {
        // Failed to allocate memory
        return;
    }

    printf("Please enter the %d items in the array...\n", *count);

    for (int i = 0; i < *count; ++i)
    {
        scanf("%d", *group + i);
        // `*group + i` is the same as `&(*group)[i]`

        ... inner loop here...
    }
}

我真的没有看到count参数成为指针的原因,除非该函数确实应该设置它。

关于的的解释

main函数中,您有一个指针变量groups。您想要分配内存并将指向该内存的指针分配给group变量。这很简单,只是

group = malloc(N * sizeof(*group));

问题的出现是因为你想在另一个函数中分配内存,这是一个问题,因为当你将一个参数传递给一个函数时,它是通过值完成的,这意味着值是复制,函数内的参数变量只是一个副本。修改副本当然不会修改原件。

如果C可以通过引用将group变量传递给函数,那么问题可以解决,这意味着函数内部的参数变量将引用 main函数中的变量。不幸的是,C没有通过引用语义传递,它只有值传递。这可以通过使用指针模拟通过引用传递来解决。

当你将一个指针传递给一个函数时,它是由值传递的指针,并被复制,试图将指针更改为指向其他位置的指针是徒劳的,因为它只会改变指针的本地副本。但是,我们可以将指向的数据更改为,这是使用取消引用运算符*完成的。使用address-of运算符&传递指向某些数据的指针。

根据上面的信息,然后如何模拟通过引用传递指针?就像任何其他变量一样,通过使用address-of运算符将指针传递给指针变量。在函数内部,我们使用dereference运算符来访问原始指针变量。

更多图形化可以看出这样的事情:

+--------------------------------+
| &group (in main function)      | -\
+--------------------------------+   \  +--------------------------+    +-----+
                                      > | group (in main function) | -> | ... |
+--------------------------------+   /  +--------------------------+    +-----+
| group (in BuildGroup function) | -/
+--------------------------------+