c - Assigning memory dynamically or on the stack based on a condition (if statement) -
i have c program in array of floats has elements accessed quite duration of program. size of array depends on argument user input , therefore vary. generally, size small enough (~ 125 elements) memory of array can placed on stack , allocation , accessing faster. in rare cases, array may large enough such requires dynamic allocation. initial solution following:
if(size < threshold){ float average[size]; } else{ float *average; average = (float*)malloc(sizeof(float) * size ); } // stuff average
this gives error @ compile time. how 1 address such problem?
the declaration of average
has limited lifetime in code; lives end of block. in other words, way declare average
makes available inside if/else
block.
i suggest splitting in 2 functions: 1 handles allocation; other work. this:
void do_average(int size, int threshold) { if (size < threshold) { float avg[size]; average(size, avg); } else { float *avg = malloc(sizeof(*avg)*size); assert(avg != null); average(size, avg); free(avg); } } void average(int avg_size, float avg[static avg_size]) { /* stuff avg */ }
you may want think how handle (unlikely) event of malloc()
returning null
. assert()
might not better choice. put there make sure don't forget check error.
note: mentioned in comments, opportunity use vla parameter declaration.
Comments
Post a Comment