Does libstruct initialize all structure fields to zero?
5 views (last 30 days)
Show older comments
Can I count on libstruct to initialize all structure fields to zero? It appears to do this for the simple test case below, but I'm not sure if this is a coincidence, or guaranteed behavior. The example is a slightly modified version of the example from the libstruct documentation.
My end use case has a large number of structures, and it would nice if I didn't need to worry about initializing everything to zero.
if ~libisloaded('shrlibsample')
addpath(fullfile(matlabroot,'extern','examples','shrlib'))
loadlibrary('shrlibsample')
end
sc = libstruct('c_struct');
disp([sc.p1, sc.p2, sc.p3])
0 Comments
Answers (1)
Umang Pandey
on 6 Dec 2023
Hi,
In MATLAB, when you create a structure that corresponds to a C struct using "libstruct", MATLAB initializes the numeric fields of the structure to default values, which for numeric types is zero.
However, for maximum reliability and to ensure that the code behaves as expected, it is recommended to explicitly initialize all fields, as demonstrated in the example below:
This practice can help prevent any unexpected behavior or deal with any special cases where the initialization might differ.
Hope this helps!
Best,
Umang
0 Comments
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!