2013-07-24 93 views
1

所以今天的练习是创建一个从0到n的函数initialize an array of intfill itC指针和malloc混淆EXC_BAD_ACCESS

我写了这个: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 
    } 
} 

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上搜索,发现这个问题了几个小时后,

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

PS:万一这是主要的使用:

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

请标记为已回答 –

+0

我还不能!不要担心我会尽快做到这一点:9更多分钟 – ItsASecret

+0

我的不好!...我很抱歉! –

回答

7

你有错误的优先级,

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

应该

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

如果没有括号,则访问

*(array[i-1]) 

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

+1

好吧,我永远不会发现,非常感谢你! – ItsASecret