C指针和malloc混淆EXC_BAD_ACCESS

Its*_*ret 1 c malloc pointers exc-bad-access

因此,今天的演习是创建一个函数initialize an array of int,并fill it从0到n.

我写了这个:

void        function(int **array, int max)
{
    int i = 0;
    *array = (int *) malloc((max + 1) * sizeof(int));
    while (i++ < max)
    {
        *array[i - 1] = i - 1; // And get EXC_BAD_ACCESS here after i = 2
    }
}
Run Code Online (Sandbox Code Playgroud)

经过几个小时的EXC_BAD_ACCESS疯狂后,我决定搜索SO,找到这个问题:在函数中初始化数组 然后将我的函数更改为:

void        function(int **array, int max)
{
    int *ptr; // Create pointer
    int i = 0;
    ptr = (int *) malloc((max + 1) * sizeof(int)); // Changed to malloc to the fresh ptr
    *array = ptr; // assign the ptr
    while (i++ < max)
    {
        ptr[i - 1] = i - 1; // Use the ptr instead of *array and now it works
    }
}
Run Code Online (Sandbox Code Playgroud)

现在它有效!但它还不足以使它工作,我真的想知道为什么我的第一种方法不起作用!对我来说,他们看起来一样!

PS:以防这是我使用的主要内容:

int main() {
    int *ptr = NULL;
    function(&ptr, 9);
    while (*ptr++) {
        printf("%d", *(ptr - 1));
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*her 7

你有错误的优先权,

*array[i - 1] = i - 1;
Run Code Online (Sandbox Code Playgroud)

应该

(*array)[i - 1] = i - 1;
Run Code Online (Sandbox Code Playgroud)

没有括号,您可以访问

*(array[i-1])
Run Code Online (Sandbox Code Playgroud)

或者array[i-1][0],没有分配给i > 1.