1
所以今天的练习是创建一个从0到n的函数initialize an array of int
和fill it
。C指针和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));
}
}
请标记为已回答 –
我还不能!不要担心我会尽快做到这一点:9更多分钟 – ItsASecret
我的不好!...我很抱歉! –