我有一个函数,函数的基本思想是改变a
指向的东西。第一个版本有效,但第二个版本无效。
有人可以帮我理解这里发生了什么吗?
// this works
void swap(int **a) {
int *temp = malloc(sizeof(int) * 3);
temp[0] = 0;
temp[1] = 1;
temp[2] = 2;
*a = temp;
}
// this does not
void swap(int **a) {
*a = malloc(sizeof(int) * 3);
*a[0] = 0;
*a[1] = 1; // seg fault occurs on this line
*a[2] = 2;
}
我这样调用函数
int main() {
int b[] = {0,1};
int *a = b;
swap(&a);
return 0;
}
此外,这两个函数不能同时属于同一个文件。