6

我有一个函数,函数的基本思想是改变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;
}

此外,这两个函数不能同时属于同一个文件。

4

1 回答 1

14

的优先级[]高于*(实际上[]在 C 中具有最高优先级)。这意味着你的表达*(a[0])不是(*a)[0]你想要的。

于 2013-03-25T18:52:21.420 回答