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?
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.
No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result.
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.
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.
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};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With