Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ help

Name: Anonymous 2011-11-07 23:46

Don't know if anyone here cares to help, but i couldn't find any answers with searching google.


I want to take the size of two arrays, add them, then dynamically allocate a new one with the size of that sum.

i can't get the new array to work outside of this function.
is there a way to pass it outside of this function?

void sizing(double *f1, double *f2, double *out1, double *out2)
{
    int x,y,z;
    x = (sizeof(f1))/ (sizeof(f1[0]));
    y = (sizeof(f2))/ (sizeof(f2[0]));
    z = x+y;

    *out1 = new double[z];
    *out2 = new double[z];
}

Name: Anonymous 2011-11-08 0:19

You've got way more problems on your hands than merely figuring out how to pass pointers by reference so that you can return the results to the caller. The sizeof operator doesn't work on pointers for determining the array length, it instead returns the size of the pointer, which is 4 or 8 bytes depending on your target architecture. Plus you've got two outputs when it's obvious you only want one.

The following code is the proper C++11 way of doing it.


#include <vector>

int main() {
   std::vector<double> f1 = { 1.0, 2.0, 3.0 };
   std::vector<double> f2 = { 4.0, 5.0, 6.0 };
   std::vector<double> result;

   std::copy(f1.begin(), f1.end(), std::back_inserter(result));
   std::copy(f2.begin(), f2.end(), std::back_inserter(result));

   // result now holds the values { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 }
   // do something with result, like print it out
   return 0;
}


Since std::vector, std::copy and std::back_inserter do all of the work for you, you don't really need to write a separate function to concatenate f1 and f2, you just need to compose the various primitives that the Standard C++ Library provides you together.

Note that it requires the new C++11 initializer list syntax for constructing f1 and f2, so with GCC 4.6+ compile with the -std=c++0x flag.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List