如何创建一个可变大小的数组,将一个变量2d数组传递给一个函数并返回另一个2d数组?

时间:2013-07-21 13:33:16

标签: c pointers multidimensional-array size

如何创建一个可变大小的二维数组,传递该变量数组,并返回一个不同维度的新二维数组?我已经工作了几个小时,我找不到解决方案。我设法为PGM图像创建一个像素值数组,但现在我正在尝试“旋转”数组,但这变得非常复杂,因为我的编译器不会让我声明一个可变大小的对象。谢谢你那些回答的人太多了。

这是调用该函数的语句。有人告诉我使用malloc因为你不能创建一个可变大小的数组。

char *SpunArray = malloc(image->x * image->y * sizeof(PGMPixel));
SpunArray = Rotate90Array(image->x, image->y, CreatedArray);

这是功能:

//char * Rotate90Array(int x, int y, char *array[x][y] )
char * Rotate90Array(int x, int y, char *array )
{
    printf("\nLine 179");
    // These have to be swapped because the image is being rotated
    char *RotatedArray = malloc(x * y * sizeof(char));
    printf("\nLine 182");
    int u = x - 1;
    int v = y - 1;
    int i = 0;
    int j = 0;
    printf("\nLine 187");
    char *ptr;
    printf("\nLine 189");
    for (i = 0; i < x; i++)
    {
        printf("\nLine 192");
        *ptr = RotatedArray[i];
        printf("\nLine 194");
        for (j = 0; j < y; j++)
        {
            printf("\nLine 197");
//          *ptr = *(array[u-j][i]);
            *(ptr+((j*x)+(u-i))) = *(array+((i*y)+j));
            printf("\nLine 200");
            ptr++;
            printf("\nLine 202");
        }
    }
    printf("\nLine 205");
    return RotatedArray;
}

我正在使用MingGW gcc,如果有帮助,则使用Windows 8.

2 个答案:

答案 0 :(得分:1)

你有内存泄漏。为什么要创建两个数组而不是一个?

这样做:

char *SpunArray = malloc(image->x * image->y * sizeof(PGMPixel));
Rotate90Array(image->x, image->y, CreatedArray, SpunArray);

void Rotate90Array(int width, int height, char *array, char *RotatedArray)
{
    int i = 0;
    int j = 0;
    for (i = 0; i < width; i++)
    {
        for (j = 0; j < height; j++)
        {
            // check this line on correct
            RotatedArray[i * height + j] = array[j * width + width - i - 1];
        }
    }
}

答案 1 :(得分:0)

我认为此代码可以按预期运行:

char * Rotate90Array(int x, int y, char *array )
{
    printf("\nLine 179");
    // These have to be swapped because the image is being rotated
    char *RotatedArray = malloc(x * y * sizeof(char));
    printf("\nLine 182");
    int u = x - 1;
    int v = y - 1;
    int i = 0;
    int j = 0;
    printf("Line 187\n");
    char *ptr;
    printf("Line 189\n");
    ptr = RotatedArray;             //I add this line
    for (i = 0; i < x; i++)
    {
        printf("Line 192\n");
       // *ptr = RotatedArray[i];   //I delete this line 
        printf("Line 194\n");
        for (j = 0; j < y; j++)
        {
            printf("Line 197\n");
//          *ptr = *(array[u-j][i]);
            *(ptr+((j*x)+(u-i))) = *(array+((i*y)+j));
            printf("Line 200\n");
        //    ptr++;                // I delete this line
            printf("Line 202\n");
        }
    }
    printf("Line 205\n");
    return RotatedArray;
}