C++ passing dynamic array element to a function -


the code looks this:

void func(float b){   //does nothing   }  float* finit(void){   float result[3];   result[0] = 1.0;   result[1] = 1.0;   result[2] = 1.0;    return result; }  int main(){   float* = new float[3];   = finit();   func(a[0]);   printf("%f, %f, %f", a[0], a[1], a[2]);    return 0; } 

values of array elements -107374176.000000. works if func(a[0]) [which nothing] commented out. what's problem?

edit: code edited bit better understanding

you cannot return raw array that. finit() return address of local memory invalidated once function returns.

your a then, in sense, points memory inside finit(), not valid anymore. attempt read element a[n] results in undefined behaviour.

you should use 1 of standard containers, e.g. std::vector if size of array determined @ runtime, or std::array if know size @ compile time. if need chained lists, use std::list, , on.

all of standard containers copyable (and returnable).

see http://en.cppreference.com/w/cpp/container.

and, definitely bookmark http://en.cppreference.com/w/. , every time tempted write algorithm, or find invoking new, reference. , get books!


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -