Main Content

Initialize Pointer Members of C++ Structures for MATLAB Interface to Library

Although your code might first allocate a struct and subsequently assign values to its members, the MATLAB® interface does not support assigning a new object to a pointer member. For example, this header defines a struct variable S2 with a member pointer to struct S1.

struct S1 {
   S1() {};
};

struct  S2 {
   S1 *s1;
   S2() {};
};

Suppose that you built this code into library lib. When you try to reference pointer s1, it points to random memory, which results in unpredictable behavior.

s2Obj = clib.lib.S2;
s2Obj.s1

To work around this issue, initialize the pointer inside the struct definition:

struct S1 {
   S1() {};
};

struct  S2 {
   S1 *s1;
   S2() {};
   S1 s1 = S1();   // initialize pointer
};