简体   繁体   中英

How to pass pointer to struct to a function?

I am instantiating the struct within the main() function and I am passing a pointer to this structure over to a function. I would like to then pass this pointer to the original struct to another function, how would I do this?

I am now lost in pointerception.

struct coords {
    int x;
    int y;
}

// Main loop, instantiated the struct
int main(void)
{
    struct coords myCoords;
    while(1) {
        doStuff(&myCoords);
    }
}

// Calculate Coords and update them via pointer to struct
// I want to be able to edit myCoords within calculateCoords
void doStuff(struct coords* myCoords)
{
    calculateCoords(&myCoords);

    calculateMotorSpeeds(&myCoords);
}

// I want to be able to edit myCoords within here!
void calculateCoords(struct coords* myCoords)
{
    myCoords->x = 100;
}

Inside your doStuff() function, myCoords is already a pointer. You can simply pass that pointer itself to calculateCoords() and calculateMotorSpeeds() function.

Also, with a function prototype like

 void calculateCoords(struct coords* myCoords)

calling

 calculateCoords(&myCoords);

from doStuff() is wrong, as it is passing struct coords** .

Solution:

Keep your function signature for calculateCoords() intact, just chnage the call to

  calculateCoords(myCoords);

and then, any changes made to any member variable through myCoords inside calculateCoords will be reflected in the myCoords in main() .

doStuff already has a pointer to your struct coords object. It doesn't need to do anything in order to pass that pointer on to other functions. So you can just define doStuff like this:

void doStuff(struct coords* myCoords)
{
    calculateCoords(&myCoords);
    calculateMotorSpeeds(&myCoords);
}

The reason why you needed to pass &myCoords to the call to doStuff in main is that there, the name myCoords refers to a struct coords object, not to a pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM