Struct of 2D Variable Length Array in C -


i trying create struct containing 2 variable length array (buffer_size variable parameter acquired @ run time). here code:

struct data {   float *c;   //2d array   float *mtdt;  //1d array };  struct data c_matrice;   c_matrice.c = malloc((90 * sizeof (float*) * buffer_size));  c_matrice.mtdt = malloc(90 * sizeof (float*)); 

the idea link structure's members arrays dynamically allocated. here compiler error

expected « = », « , », « ; », « asm » or « __attribute__ » before « . » token  c_matrice.c = malloc((90 * sizeof (float*) * buffer_size)); 

and when try access members,

subscripted value neither array nor pointer nor vector 

i haven't been able find solution problem in previous questions. frankly beginner don't everything. missing?

edit 1: ok got rid of first error moving last 2 lines main.c rather .h file (this basic stupid mistake). still face the

subscripted value neither array nor pointer nor vector 

when try access struct this

pmoy = pow(10,(c_matrice->c[i][curve2apply]/20))*pmax; 

and way, whole code big, , presented small part of actual code.

what you've done here:

c_matrice.c = malloc((90 * sizeof (float*) * buffer_size));  

is allocate 1 long buffer of size 90 * size of pointer-to-float * buffer_size.

you have bunch of options in how implement 2d array in c. 1 approach change have there to:

c_matrice.c = malloc((90 * sizeof (float) * buffer_size));  

so you've allocated space 90*buffer_size floats (rather pointers floats).

you need calculate indexes yourself:

float get_matrix_element(struct data *c_matrix, size_t row, size_t column)  {           return c_matrix->c[row*buffer_size+column]; } 

that's popular , efficient way of storing data because it's stored 1 block of memory , can useful things allocate in single block , iterate through without concern structure:

float get_matrix_sum(struct data *c_matrix)  {           size_t sz=buffer_size*90;     float sum=0.0f;     for(size_t i=0;i<sz;++i){        sum+=c_matrix->c[i];     }     return sum; } 

there other ways of doing including:

  1. declare 90 long 1d array of pointers float , allocate rows of floats.

the downside 91 malloc()/free() operations instead of 1. upside allocate ragged array different length rows.

  1. declare static (compile time) sized array float c[90][buffer_size];

where buffer_size compile time constant. downside it's compile time fixed (and if large , local variable may break stack). upside managing internal r*90+c row calculation taken off you.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -