如何修改傳遞給C中函數(shù)的指針?因此,我有一些代碼,類似于下面的代碼,可以將結(jié)構(gòu)添加到結(jié)構(gòu)列表中: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}這些結(jié)構(gòu)的定義如下:typedef struct Bar{
// this isn't too important} Bar;#define EMPTY_LIST NULLtypedef struct BarList{
Bar * val;
struct BarList * nextBar;} BarList;然后在另一個(gè)文件中執(zhí)行如下操作:BarList * l;l = EMPTY_LIST;barPush(l,&b1); // b1 and b2 are just Bar'sbarPush(l,&b2);但是,在此之后,l仍然指向空_list,而不是barPush內(nèi)部創(chuàng)建的修改版本。如果我想修改一個(gè)指針,是否必須將列表作為指針傳入,還是需要使用其他暗咒語?
3 回答

函數(shù)式編程
TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
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'sbarPush(&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'sl = barPush(l,&b2);

幕布斯6054654
TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
int myFunction(int** param1, int** param2) {// now I can change the ACTUAL pointer - kind of like passing a pointer by reference }
- 3 回答
- 0 關(guān)注
- 651 瀏覽
添加回答
舉報(bào)
0/150
提交
取消