2009-04-20 66 views
34

所以,我有一些代码,有点像下面的结构增加结构的列表:如何修改已传递到C中函数的指针?

void barPush(BarList * list,Bar * bar) 
{ 
    // if there is no move to add, then we are done 
    if (bar == NULL) return;//EMPTY_LIST; 

    // allocate space for the new node 
    BarList * newNode = malloc(sizeof(BarList)); 

    // assign the right values 
    newNode->val = bar; 
    newNode->nextBar = list; 

    // and set list to be equal to the new head of the list 
    list = newNode; // This line works, but list only changes inside of this function 
} 

这些结构的定义如下:

typedef struct Bar 
{ 
    // this isn't too important 
} Bar; 

#define EMPTY_LIST NULL 

typedef struct BarList 
{ 
    Bar * val; 
    struct BarList * nextBar; 
} BarList; 

,然后在另一文件我做类似如下:

BarList * l; 

l = EMPTY_LIST; 
barPush(l,&b1); // b1 and b2 are just Bar's 
barPush(l,&b2); 

然而,在此之后,L仍然指向EMPTY_LIST,不barPush内创建的修改后的版本。如果我想修改它,还是需要其他一些黑暗咒语,我是否必须将列表作为指针传入指针?

回答

41

,如果你想做到这一点你必须在一个指针传递给一个指针。

void barPush(BarList ** list,Bar * bar) 
{ 
    if (list == NULL) return; // need to pass in the pointer to your pointer to your list. 

    // if there is no move to add, then we are done 
    if (bar == NULL) return; 

    // allocate space for the new node 
    BarList * newNode = malloc(sizeof(BarList)); 

    // assign the right values 
    newNode->val = bar; 
    newNode->nextBar = *list; 

    // and set the contents of the pointer to the pointer to the head of the list 
    // (ie: the pointer the the head of the list) to the new node. 
    *list = newNode; 
} 

然后使用它是这样的:

BarList * l; 

l = EMPTY_LIST; 
barPush(&l,&b1); // b1 and b2 are just Bar's 
barPush(&l,&b2); 

乔纳森·莱弗勒提出的意见返回列表的新掌门人:

BarList *barPush(BarList *list,Bar *bar) 
{ 
    // if there is no move to add, then we are done - return unmodified list. 
    if (bar == NULL) return list; 

    // allocate space for the new node 
    BarList * newNode = malloc(sizeof(BarList)); 

    // assign the right values 
    newNode->val = bar; 
    newNode->nextBar = list; 

    // return the new head of the list. 
    return newNode; 
} 

用途变为:

BarList * l; 

l = EMPTY_LIST; 
l = barPush(l,&b1); // b1 and b2 are just Bar's 
l = barPush(l,&b2); 
+1

谢谢,我想这是问题所在,但希望它不是;) – 2009-04-20 04:38:52

2

是的,你必须传入指针指针。 C通过值传递参数,而不是通过引用。

6

请记住,在C中,一切都是按价值传递的。

你在一个指针传递到指针,这样

int myFunction(int** param1, int** param2) { 

// now I can change the ACTUAL pointer - kind of like passing a pointer by reference 

} 
2

这是一个经典的p roblem。返回分配的节点或使用指针指针。在C中,你应该将一个指针传递给一个你希望修改X的函数。在这种情况下,既然你想要一个指针被修改,你应该把一个指针传给一个指针。

14

通用答案:将指针传递给要更改的内容。

在这种情况下,它将是您想要更改的指针的指针。