C ++ Updating a data item with a struct pointer

I have a question that should be easy. I have a global function (setData) that takes a pointer to my test structure. When I try to update a data item, it does not work.

#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);
}
+3
source share
7 answers

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

Yes you are right! Your code produces a copy, modifies it, and then quickly discards it.

Instead, you should change the structure passed through the pointer:

tp -> data = newData;

Pay attention to the operator ->. This is the equivalent of an access operator pointer .. It is equivalent

(*tp).data = newData;

but he looks better.

You can do the same in printData, although this is simply inefficiency:

cout << tp -> data;
+1
source

, setData, . :

void setData(test* tp, int newData) {
    tp->data = newData;
}
+1
test t = *tp;

. , . :

tp->data = newData;

, ++.

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

. . :

tp->data = newdata;
+1

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

setData test. test, :

void setData(test* tp, int newData) {
    t->data = newData;
}

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

setData() struct.

:

void setData(test* tp, int newData) {
    test t = *tp;
    t.data = newData;
    *tp = t;
}

:

void setData(test* tp, int newData) {
    tp->data = newData;
}

.

0

You only change the local variable. Do it instead

tp->data = newData;
0
source

All Articles