Previous: Using Variable Length Types, Continued Next: Sea Sounding Example Table of contents Frames User guide
2009 Unidata NetCDF Workshop for Developers and Data Providers > User Defined Types in NetCDF-4

23.17 Sea Sounding Example Code
This example shows a variable length array inside a compound type.

 

   int ncid, dimid, varid, temp_typeid, sounding_typeid;
   struct sea_sounding
   {
	 int sounding_no;
	 nc_vlen_t temp_vl;
   } data[DIM_LEN];
   float *phoney;
   int i, j;

   /* Create phoney data. */
   for (i=0; i < DIM_LEN; i++)
   {
      if (!(phoney = malloc(sizeof(float) * i+1)))
	 return NC_ENOMEM;
      for (j = 0; j < i + 1; j++)
	 phoney[j] = 23.5 - j;
      data[i].temp_vl.p = phoney;
      data[i].temp_vl.len = i+1;
   }

   /* Create a netcdf-4 file. */
   if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

   /* Create the vlen type, with a float base type. */
   if (nc_def_vlen(ncid, "temp_vlen", NC_FLOAT, &temp_typeid)) ERR;

   /* Create the compound type to hold a sea sounding. */
   if (nc_def_compound(ncid, sizeof(struct sea_sounding), 
		       "sea_sounding", &sounding_typeid)) ERR;
   if (nc_insert_compound(ncid, sounding_typeid, "sounding_no", 
			  NC_COMPOUND_OFFSET(struct sea_sounding, sounding_no), 
			  NC_INT)) ERR;
   if (nc_insert_compound(ncid, sounding_typeid, "temp_vl", 
			  NC_COMPOUND_OFFSET(struct sea_sounding, temp_vl), 
			  temp_typeid)) ERR;

   /* Define a dimension, and a 1D var of sea sounding compound type. */
   if (nc_def_dim(ncid, DIM_NAME, DIM_LEN, &dimid)) ERR;
   if (nc_def_var(ncid, "fun_soundings", sounding_typeid, 1, 
		  &dimid, &varid)) ERR;

   /* Write our array of phone data to the file, all at once. */
   if (nc_put_var(ncid, varid, data)) ERR;

   /* We're done, yipee! */
   if (nc_close(ncid)) ERR;

 


Previous: Using Variable Length Types, Continued Next: Sea Sounding Example Table of contents Frames User guide
2009 Unidata NetCDF Workshop for Developers and Data Providers > User Defined Types in NetCDF-4