Bas Jansen
Bas Jansen

Reputation: 3343

Adressing values of a nested structure in C

I have a nested structure as follows:

typedef struct {
   float mz_value;
   float int_value;
} spectrum;
typedef struct {
   // stuff
   spectrum* spectra; /* Nested struct */
   // more stuff
} chromatogram;

I allocate memory in my code as follows:

(chrom+i)->spectra=malloc(sizeof(spectrum)*1024);

I then want to assign some values to it and I have been trying all kinds of syntaxes similar to:

((chrom+i)->(spectra+j))->mz_value = (float)*(array_buffer+j);
// array_buffer is a float*

Yet this keeps giving me an error that I am failing at proper usages of braces, the only problem is that I can't figure out where o.O Any help would be greatly appreciated before I regret trying to use a nested structure.

Cheers, Bas

Upvotes: 1

Views: 528

Answers (2)

Vladimir
Vladimir

Reputation: 7801

Your spectra value is not a statically allocated structure it's a pointer and you need allocate memory for it.

If you are going to work with fixed number of spectrum items use statically allocated array

spectrum spectra[someConstantValue]; 

or allocate/free it dynamically, in this case you also need to hold number of elements.

typedef struct {
   // stuff
   spectrum* spectra; /* Nested struct */
   int count;
   // more stuff
} chromatogram;

Upvotes: 0

Martin B
Martin B

Reputation: 24140

Try

((chrom+i)->spectra+j)->mz_value = (float)*(array_buffer+j);

Or, preferably, use array notation, which is much clearer in this case:

chrom[i].spectra[j].mz_value = (float)array_buffer[j];

Upvotes: 4

Related Questions