2007 Unidata NetCDF Workshop for Developers and Data Providers > Using NetCDF-4 Features, Part 1
12.9 The New String Type in NetCDF-4
The string type can efficiently store arrays of variable length
strings.
- String are arrays of char * from C.
- The HDF5 library allocates memory for strings when they are read,
and the memory must be freed with nc_free_string.
- Strings must be null-terminated.
- The string type may be used as an attribute, variable, or withing
a user-defined type.
#define MOBY_LEN 16
char *data[]={"Perhaps a very little thought will now enable you to account for ",
"those repeated whaling disasters--some few of which are casually ",
"chronicled--of this man or that man being taken out of the boat by ",
"the line, and lost.",
"For, when the line is darting out, to be seated then in the boat, ",
"is like being seated in the midst of the manifold whizzings of a ",
"steam-engine in full play, when every flying beam, and shaft, and wheel, ",
"is grazing you.",
"It is worse; for you cannot sit motionless in the heart of these perils, ",
"because the boat is rocking like a cradle, and you are pitched one way and ",
"the other, without the slightest warning;",
"But why say more?",
"All men live enveloped in whale-lines.",
"All are born with halters round their necks; but it is only when caught ",
"in the swift, sudden turn of death, that mortals realize the silent, subtle, ",
"ever-present perils of life."};
char *data_in[MOBY_LEN];
if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
if (nc_def_dim(ncid, DIM_NAME, MOBY_LEN, dimids)) ERR;
if (nc_def_var(ncid, VAR_NAME, NC_STRING, NDIMS, dimids, &varid)) ERR;
if (nc_put_var_string(ncid, varid, (const char **)data)) ERR;
if (nc_close(ncid)) ERR;
/* Check it out. */
if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
if (nc_get_var_string(ncid, varid, data_in)) ERR;
for (i = 0; i < MOBY_LEN; i++)
if (strcmp(data_in[i], data[i])) ERR;
if (nc_free_string(MOBY_LEN, (char **)data_in)) ERR;
if (nc_close(ncid)) ERR;
2007 Unidata NetCDF Workshop for Developers and Data Providers > Using NetCDF-4 Features, Part 1