如何将2D数组返回到C中的函数?

Eas*_*onk 23 c

我是一名Ruby程序员,最终为C开发代码生成.就像要求Limo拖着一辆20世纪60年代的卡车一样.无论如何.

这是我认为应该工作,但不起作用.

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

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

//inside main
drawLine(pixels());
Run Code Online (Sandbox Code Playgroud)

我把头撞在桌子上,试图让这件事情发挥作用.请帮忙.

asc*_*ler 25

你可怜的东西.在C中,指针和数组密切相关.此外,您通常需要将数组的大小作为单独的变量传递.让我们开始:

#include <stdio.h>

float** createArray(int m, int n)
{
    float* values = calloc(m*n, sizeof(float));
    float** rows = malloc(n*sizeof(float*));
    for (int i=0; i<n; ++i)
    {
        rows[i] = values + i*m;
    }
    return rows;
}

void destroyArray(float** arr)
{
    free(*arr);
    free(arr);
}

void drawLine(const float** coords, int m, int n);

int main(void)
{
    float** arr = createArray(2,2);
    arr[0][0] = 1;
    arr[0][1] = 1;
    arr[1][0] = 2;
    arr[1][1] = 2;
    drawLine(arr, 2, 2); 
    destroyArray(arr);
}
Run Code Online (Sandbox Code Playgroud)

  • @Alex 您是否可能将其编译为 C++ 代码?它是有效的 C 和无效的 C++。 (2认同)

Mah*_*esh 6

在 中C/C++,当您将数组传递给函数时,它会衰减为指向数组第一个元素的指针。因此,在pixels()函数中,您正在返回堆栈分配变量的地址。返回变量的地址不再有效,因为在pixels()返回时,堆栈分配的变量超出范围。因此,您应该使用动态存储的变量(即,使用 malloc、calloc)。

因此,对于二维数组,您可以使用float** arrayVariable;. 此外,如果您将它传递给一个函数,您应该注意它有多少行和列。

int rows, columns;

float** pixels()
{
    // take input for rows, columns
    // allocate memory from free store for the 2D array accordingly
    // return the array
}

void drawLine( float** returnedArrayVariable )
{
  //drawing the line
}
Run Code Online (Sandbox Code Playgroud)

由于 2D 数组自己管理资源,因此它应该使用free将资源返回到免费存储。


Eas*_*onk 6

感谢大家的回答,特别是对数组指针关系的详细解释。

我将数组封装在一个结构中

 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);
Run Code Online (Sandbox Code Playgroud)


Eun*_*ice 6

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

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

//inside main
drawLine(pixels());
Run Code Online (Sandbox Code Playgroud)