Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this struct getting set in a function

I'm trying to pass a struct pointer to a function and initialize the struct via pointer. Any idea why this isn't working?

struct Re
{
    int length;
    int width;
};

void test (Re*);

int main()
{
    Re* blah = NULL;
    test(blah);
    cout << blah->width;
    return 0;
}

void test(Re *t) {
    t = new Re{5, 5};
}

What am I doing wrong?

like image 796
whoknows Avatar asked Nov 02 '13 03:11

whoknows


People also ask

How do you pass a struct in a function?

Passing of structure to the function can be done in two ways: By passing all the elements to the function individually. By passing the entire structure to the function.

Can you declare a struct in a function?

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result.

Can a struct have functions C++?

Structs can have functions just like classes. The only difference is that they are public by default: struct A { void f() {} }; Additionally, structs can also have constructors and destructors.

Can you directly assign a struct?

Yes, you can assign one instance of a struct to another using a simple assignment statement. In the case of non-pointer or non pointer containing struct members, assignment means copy. In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.


1 Answers

The pointer is copied into the function, as it is passed by value. You must pass a pointer to a pointer or a reference to a pointer in order to initialize it:

void test(Re *&t) {
    t = new Re{5, 5};
}
like image 186
xorguy Avatar answered Oct 15 '22 07:10

xorguy