You're getting a segfault because rather than field_names
pointing to somewhere you can treat as an array of const char *
, it points nowhere because it's uninitialised. Hence
const char **field_names; /* pointer to nowhere */
...
field_names[0] = "date"; /* dereferences invalid pointer and BANG */
What you want is actually:
const char *field_names[15]; /* array of pointers to const char */
...
field_names[0] = "date"; /* all is well and good */
...
Key C fact: pointers are not arrays and arrays are not pointers, but in some circumstances an array will be implicitly converted to a pointer to its first element - such that it is still correct to pass this field_names
array to mxCreateStructMatrix()
in place of a const char **
.
However, fix that and you'll then hit the problems with this:
plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
Firstly, since you haven't checked that nlhs
is at least 2, plhs[1]
may well not exist and similarly blow up when you try to set its value. IIRC, setting plhs[0]
without checking is probably OK, since even if nlhs == 0
, plhs[0]
should point to Ans
instead of an explicit output variable, but really it's good practice to check nlhs
before doing anything and act accordingly. Similarly using prhs[0]
without checking nrhs > 0
isn't advisable.
Secondly, later on you'll end up assigning this same mxArray
to multiple fields of multiple structures which is not a valid thing to do (and may cause Matlab to crash later due to heap corruption). Even if it were allowed I don't think you want every numeric field in the whole structure array pointing to one single double
that's been overwritten n-thousand times...
Third, I don't quite understand the use of plhs[1]
at all, unless you really do want a mandatory second output of "whatever the last number read was". What I suspect you were going for is this:
mxArray *mxtmp;
...
/* in parsing loop */
mxtmp = mxCreateDoubleScalar(atof(temp));
mxSetFieldByNumber(plhs[0], i, mva_field, mxtmp);
Elsewhere, whilst indeed you can store char
values in pointers, it's not a sane or meaningful thing to do and in this case is clearly another mistake:
char *buf[1024]; /* array of pointers to char - wrong */
char *temp[20];
char buf[1024]; /* array of char - right */
char temp[20];