0

New to c++ Return an array from a function using an array as a parameter. I am working with openGL and using a 2d array to build a color table. I want to call a function that returns a 2d array from an existing 2d array. This code compiles but I want void buildArray(float color[4][3]) to return an array float color256[256][3] = {}; I understand I probably have array initialization errors. In other words. I know there are different ways to initialize arrays (pointers) I've written more C than C++ obliviously.

#include <stdio.h>
#include <iostream> 
using namespace std; 

void buildArray(float color[4][3]){
    float color256[256][3] = {};
    int n;
    float sr,sg,sb,er,eg,eb,ir,ig,ib;
    sr = color[0][0];sg = color[0][1];sb = color[0][2];
    er = color[1][0];eg = color[1][1];eb = color[1][2];
    ir = (er-sr)/8;ig = (eg-sg)/8; ib = (eb-sb)/8;
    cout<<"increments "<<ir<<" "<<ig<<" "<<ib<<endl;
    color256[0][0] = color [0][0];
    color256[0][1] = color[0][1];
    color256[0][2] = color[0][2];
    cout<<"start "<<color256[0][0]<<" "<<color256[0][1]<<" "<<color256[0][2]<<endl;
    for (n = 0; n < 8; n ++){
      color256[n+1][0] = color256[n][0] + ir;
      color256[n+1][1] = color256[n][1] + ig;
      color256[n+1][2] = color256[n][2] + ib;
      cout << color256[n][0]<<" "<<color256[n][1]<<" "<<color256[n][2]<<endl;
    }
    for (n =0;n < 8 ; n++){
      cout << color256[n][0]<<" "<<color256[n][1]<<" "<<color256[n][2]<<endl;
    }

}

void arrayStart(){
  float color[4][3]= {
  {  0.0 , 0.1686 , 0.2117 },
  {   0.0274 , 0.2117 , 0.2588},
  {   0.3450 , 0.4313 , 0.4588},
  {   0.3960 , 0.4823, 0.5137}
};
//  float c256 = color buildArray(color);
  buildArray(color);
//  for (int i =0 ;i < 8 ; i++)
//    cout << c256[i][0];
}

int main(int argc, char **argv)
{
    arrayStart();
    return 0;
}
icebowl
  • 5
  • 2
  • 1
    In C++ it's very easy to do, if you just stop using simple raw C-style arrays, and instead use e.g. [`std::array`](https://en.cppreference.com/w/cpp/container/array). – Some programmer dude Dec 31 '18 at 15:48
  • I got this to work with a 1D array . Please throw me a bone on how to implement a 2D array. #include #include using namespace std; float* myfunc(){ static float arr[2]; float count = 1.1; for (int n = 0; n < 3; n++){ arr[n] = count; count = count + 0.1; } return arr; } int main(int argc, char **argv) { float *myarray; myarray=myfunc(); for (int n = 0; n < 3; n++){ cout << myarray[n]<<" "; } cout< – icebowl Dec 31 '18 at 17:11
  • Instead of declaring a built in 2d array like `int a[3][4];` declare it using std::array like this `std::array,3> a;` Then you can use it the same way. Better, it has extensions that let you do things like copy it (return it from a function)and determine other attributes in code. And it's just as fast! – doug Jan 01 '19 at 05:40

0 Answers0