所以今天的练习是创建一个函数来初始化一个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/