C编程问题:在函数中传递,创建和返回结构。

时间:2013-07-21 16:11:47

标签: c function pointers structure

此功能不起作用,我无法弄清楚原因。它编译得很好,程序似乎运行,但经过仔细检查和调试,我发现:

newImg->x = b;
newImg->y = a;

实际上没有工作,这会导致问题。我尝试使用newImg = img进行复制,但这不允许我稍后更改newImg的值。它们仍然完全相同。我也尝试修改img的值,然后执行newImg,但调试显示newImg正在获得极值。

这是结构:

typedef struct
{
     unsigned char grayscale;
} PGMPixel;

typedef struct
{
     int x, y;
     PGMPixel *data;
} PGMImage;

这是功能:

static PGMImage *rotatePGM(PGMImage *img)
{   
    PGMImage *newImg;


    // Memory allocation for pgm
    newImg = (PGMImage *)malloc(sizeof(PGMImage));
    if (!newImg) 
    {
         fprintf(stderr, "Unable to allocate memory\n");
         exit(1);
    }

    //memory allocation for pixel data
    newImg->data = (PGMPixel*)malloc(newImg->x * newImg->y * sizeof(PGMPixel));
    if (!newImg) 
    {
         fprintf(stderr, "Unable to allocate memory\n");
         exit(1);
    }

    int a = img->x;
    int b = img->y;
    newImg->x = b;
    newImg->y = a;  

    int u = a - 1;
    int v = b - 1;
    int i = 0;
    int j = 0;

    if(newImg)
    {
        for (i = 0; i < a; i++)
        {
            for (j = 0; j < b; j++)
            {
                img->data[(j*a)+(u-i)].grayscale = img->data[(i*b)+j].grayscale;
            }
        }
    }   
    return newImg;
}

如果有帮助,我正在使用MinGW GCC和Windows 8。

2 个答案:

答案 0 :(得分:2)

该行

newImg->data = (PGMPixel*)malloc(newImg->x * newImg->y * sizeof(PGMPixel));

错误 - 它在初始化之前使用newImg->xnewImg->y。您应该使用img中的值来代替

newImg->data = malloc(img->x * img->y * sizeof(PGMPixel));

我对该行进行了另一项小改动 - you don't need to cast the return from malloc

您也会在行

中稍后使用错误的PGMPixel实例
img->data[... = img->data[...

(大概应该是newImg->data分配给你)

答案 1 :(得分:2)

newImg-&gt; data =(PGMPixel *)malloc(newImg-&gt; x * newImg-&gt; y * sizeof(PGMPixel));

这里没有初始化变量。