0

如何创建一个可变大小的二维数组,传递该可变数组,并返回一个不同维度的新二维数组?我已经为此工作了几个小时,但找不到解决方案。我设法为 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。

4

2 回答 2

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];
        }
    }
}
于 2013-07-21T13:49:59.047 回答
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;
}
于 2013-07-21T15:08:17.907 回答