Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Updating a data member using a struct pointer

Tags:

c++

struct

I have what should be an easy question. I have a global function (setData) which takes a pointer to my test struct. When I try to update the data member it is not working.

#include <iostream>
using namespace std;

struct test {
    int data;
};

void setData(test* tp, int newData) {
    test t = *tp;    // I think the problem is here.
    t.data = newData;
}

void printData(test* tp) {
    test testStruct = *tp;
    cout << testStruct.data;
}

int main()
{
    test ts;
    ts.data = 22;
    setData(&ts, 44);
    printData(&ts);
}
like image 500
Cromos Avatar asked Oct 28 '25 04:10

Cromos


1 Answers

test t = *tp; // I think the problem is here.

Yes, you are right! Your code is making a copy, modifies it, and then promptly discards.

You should instead modify the structure passed in through a pointer:

tp -> data = newData;

Note the -> operator. It is the pointer equivalent of the . member access operator. It is equivalent to

(*tp).data = newData;

but it looks nicer.

You can do the same thing in the printData, although it is merely an inefficiency there:

cout << tp -> data;
like image 60
Sergey Kalinichenko Avatar answered Oct 29 '25 18:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!