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

时间:2011-03-05 04:36:37

标签: 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());

我把我的头撞在桌子上试图让这件事情起作用。请帮忙。

5 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:5)

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());

答案 2 :(得分:4)

谢谢大家的答案,更具体地说是对阵列指针关系的详细解释。

我将数组封装在结构

 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);

答案 3 :(得分:3)

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

因此,对于二维数组,您可以使用float** arrayVariable;。此外,如果你将它传递给一个函数,你应该警惕多少行&amp;它有的列。

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
}

由于2D阵列正在自行管理资源,因此应使用 free 将资源返回到免费商店。

答案 4 :(得分:1)

最简单的方法可能是在main中声明float数组并让pixels填充它:

#define PIXEL_X_SIZE 2
#define PIXEL_Y_SIZE 2

int pixels(float x[][PIXEL_X_SIZE], int len) {
    /* I don't know if you want the logic of this method to ever change,
       but this will be roughly equivalent to what you do above */
    if (len < PIXEL_Y_SIZE) {
        /* the length of the passed array is too small, abort */
        return -1;
    }

    x[0][0] = x[0][1] = 1;
    x[1][0] = x[1][1] = 2;
    return 0;
}

void drawLine(float x[][PIXEL_X_SIZE]) {
    /* this will work fine */
}

int main() {
    float pixel_array[PIXEL_Y_SIZE][PIXEL_X_SIZE];
    pixels(pixel_array, PIXEL_Y_SIZE);
    drawLine(pixel_array);
}

你也可以使用mallocfree并将你的像素存储在堆上,但如果像素阵列的数量越大,就没有必要,它只是增加额外的复杂性,以确保您的记忆总是得到适当的分配和释放。