[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[netCDF #DXE-930963]: example code for using scalar string variables



Hello Alex,

My sincere apologies for the delayed response.  Your code largely looks fine, 
except you need to allocate memory for `data_in`.  When deciding on the size of 
the variable you'll be reading in to, you should ensure it is large enough for 
the characters AND to hold the terminating null character at the end.  The 
string should be null terminated when read, so it is safe to allocate a larger 
variable than you will need.

I hope this helps and again please accept my apologies for the delayed response!

-Ward



> Hello!
> 
> I am trying to use C API to store and retrieve a scalar string. Here is
> my code which seems to work. Could you please take a look at let me know
> whether the API is used as intended:
> 
> #define ERR (fprintf(stderr, "Error on line %d of %s.", __LINE__, __FILE__))
> 
> int main()
> {
>    int  ncid = 0;
>    int char_varid = 0;
> 
>    if(nc_create("test.nc", NC_NETCDF4, &ncid)) ERR;
>    if(nc_def_var(ncid, "String_Var", NC_STRING, 0, 0, &char_varid)) ERR;
>    if(nc_enddef(ncid)) ERR;
> 
>    const char *data_in = "Test string.";
>    if(nc_put_var_string(ncid, char_varid, &data_in)) ERR;
> 
>    char *data_out = NULL;
>    if(nc_get_var_string(ncid, char_varid, &data_out)) ERR;
> 
>    std::cout << "Retrieved: " << data_out << std::endl;
>    free(data_out);
> 
>    if(nc_close(ncid)) ERR;
>    return 0;
> }
> 
> Thanks,
> 
> Alex
> 
> 


Ticket Details
===================
Ticket ID: DXE-930963
Department: Support netCDF
Priority: High
Status: Closed
===================
NOTE: All email exchanges with Unidata User Support are recorded in the Unidata 
inquiry tracking system and then made publicly available through the web.  If 
you do not want to have your interactions made available in this way, you must 
let us know in each email you send to us.