どのように私はC言語で関数に渡されたポインタを変更していますか?

StackOverflow https://stackoverflow.com/questions/766893

  •  12-09-2019
  •  | 
  •  

質問

だから、私は構造体のリストに構造体を追加するために、種類の以下のような、いくつかのコードを持っています:

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は依然として、barPushの内部に作成されていない修正バージョンをEMPTY_LISTを指します。私はそれを変更したい場合は、ポインタへのポインタとしてリストを渡すために持っているか、必要ないくつかの他の暗い呪文はありますか?

役に立ちましたか?

解決

あなたはこれをしたい場合は、ポインタへのポインタを渡す必要があります。

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

他のヒント

一般的な答えは:変更したいものへのポインタを渡します。

この場合、それはあなたが変更したいポインタへのポインタになります。

Cで、すべてが値によって渡され、覚えています。

は、

このように、ポインタへのポインタを渡します
int myFunction(int** param1, int** param2) {

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

}

はい、あなたは、ポインタへのポインタで渡す必要があります。 Cはない参照することによって、値で引数を渡します。

これは古典的な問題があります。割り当てられたノードを返すか、ポインタのポインタを使用しますか。 Cでは、あなたはあなたのXを変更したい機能にXへのポインタを渡す必要があります。あなたはポインタを変更することにしたいので、この場合は、あなたがポインタへのポインタを渡すべきである。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top