Search code examples
carraysreturn

How to return a 2D array from a function in C?


I am a Ruby programmer who has ended up developing a code generate for C. Its like asking a Limo to tow a 1960s truck. Any way.

Here is what I thought should work but doesnt work.

float[][] pixels()
{
  float x[][]= { {1,1},{2,2} };
  return x
}

void drawLine(float x[][2])
{
  //drawing the line
}

//inside main
drawLine(pixels());

I have banged my head on my desk trying to get this thing work. Please help.


Solution

  • Thank you all for your answers and more specifically for the detailed explanation of the array-pointer relationship.

    I encapsulated the array in a structure

     struct point_group1 {
            float x[3];
            float y[3];
    };
    
    struct point_group1 pixels(){
        struct point_group1 temp;
    
        temp.x[0] = 0.0;
        temp.x[1] = 1.0;
        temp.x[2] = -1.0;
    
        temp.y[0] = 0.0;
        temp.y[1] = 1.0;
        temp.y[2] = 1.0;
    
        return temp;    
    }
    
    
    
    struct point_group1 points1  = pixels();
    axPoly(points1.x, points1.y ,3, 0.0);