C:传递指针的地址与传递数组的地址

时间:2017-04-12 04:34:31

标签: c arrays pointers

这是我几天前的一个远程编码测试,我已经提交了答案,所以我不会在这里作弊。

问题很简单:实现一个从链表中删除项目的功能。但有一个问题:链表是一个数组的形式。

typedef struct _Node{
    int val;
    struct _Node* next;
} Node;

面试官提供的测试输入,我们可以稍微修改

void printLL(Node* root){
    Node* current = root;
    while (current){
        printf("%d\n", current->val);
        current = current->next; 
    }
}

int main(){
   Node list[6];
   list[0].value =1; list[0].next = list+1;
   list[1].value =2; list[1].next = list+2;
   list[2].value =3; list[2].next = list+3;
   list[3].value =4; list[3].next = list+4;
   list[4].value =5; list[4].next = list+5;
   list[5].value =6; list[5].next = 0;

   delete(&list, 3) // this gives segmentation error with my implementation;
   printLL(list);
   return 0;
}

我的回答,这是链表删除的标准:

void delete(Node** root, int val){
    Node* current = *root;
    Node* prev = NULL;

    if ((*root)->val == val){
        *root = (*root)->next;
        //free(current); // test case not dynamically allocated
        return;
    }
    while (current && (current->val != val)){
        prev = current;
        current = current->next;
     }
    if (!current){
       printf("value not found\n");
       return ;
     }
    else{
       prev->next = current->next;
       //free(current);
    }
}

但是,如果我使用指针代替,那么函数可以正常工作

 Node* p = list;
 delete(&p, 3);

我想我理解& list和& p之间的区别是函数参数:

**Variable name  |  Variable value      |     Variable address**

list             | address of first elem |     address of first elem

p                | address of first elem | some random address of the pointer

但是因为在delete函数中我们分别使用* list和* p操作,所以它们的值也应该相同。

我现在的猜测是因为

   *root = (*root)->next;

如果* root是一个数组名称,那么它是非法的,因为我们无法重新分配它。但如果* root是指针,那么我们可以自由地重新分配它们。我对此是否正确?

感谢您阅读这篇漫长而凌乱的文章。

0 个答案:

没有答案