亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何修改傳遞給C中函數的指針?

如何修改傳遞給C中函數的指針?

C++ C
慕慕森 2019-06-11 13:46:19
如何修改傳遞給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 NULLtypedef struct BarList{     Bar * val;     struct  BarList * nextBar;} BarList;然后在另一個文件中執行如下操作:BarList * l;l = EMPTY_LIST;barPush(l,&b1); // b1 and b2 are just Bar'sbarPush(l,&b2);但是,在此之后,l仍然指向空_list,而不是barPush內部創建的修改版本。如果我想修改一個指針,是否必須將列表作為指針傳入,還是需要使用其他暗咒語?
查看完整描述

3 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

如果要這樣做,則需要傳入指向指針的指針。

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);

喬納森·萊弗勒(JonathanLeffler)建議將評論中的新頭目返回:

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);


查看完整回答
反對 回復 2019-06-11
?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

一般答案:傳遞指向要更改的內容的指針。

在這種情況下,它將是指向要更改的指針。


查看完整回答
反對 回復 2019-06-11
?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

記住,在C中,一切都是通過值傳遞的。

傳入指向指針的指針,如下所示

int myFunction(int** param1, int** param2) {// now I can change the ACTUAL pointer - kind of like passing a pointer by reference }


查看完整回答
反對 回復 2019-06-11
  • 3 回答
  • 0 關注
  • 656 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號