C 指针和 malloc 混淆 EXC_BAD_ACCESS

标签 c pointers malloc exc-bad-access

所以今天的练习是创建一个函数来初始化一个int数组填充它从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
    }
}

EXC_BAD_ACCESS 几个小时后,我快疯了,我决定搜索 SO,找到这个问题:Initialize array in function 然后将我的功能更改为:

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
    }
}

现在可以了!但这还不够,我真的很想知道为什么我的第一种方法不起作用!对我来说,它们看起来一样!

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

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

最佳答案

你有错误的优先级,

*array[i - 1] = i - 1;

应该是

(*array)[i - 1] = i - 1;

没有括号,你访问

*(array[i-1])

array[i-1][0],不分配给i > 1

关于C 指针和 malloc 混淆 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17839186/

相关文章:

c - C中的初始化部分

C 编程 : Preprocessor, 包含来自宏的文件

c++ - C/C++ 中的嵌套位域

c - 如何在函数中检查 C 中的类型

c - 访问链接列表或在 Linux 上执行 malloc() 时出现段错误

c - 这段代码会导致内存泄漏吗?

c - 释放分配的二叉树 - C 编程

c - C语言软件设计实践

c - 使用指针的函数调用

delphi - 从指针复制数据?