【问题标题】:C Programming Issues: Passing, creating, and returning structures in functions.C 编程问题:在函数中传递、创建和返回结构。
【发布时间】:2013-07-21 16:11:47
【问题描述】:

这个功能不起作用,我不知道为什么。它编译得很好,程序似乎可以运行,但是经过仔细检查和调试,我发现:

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。

【问题讨论】:

  • 你初始化img-&gt;ximg-&gt;y了吗?您看到分配给newImg 的值是什么?
  • 您不需要在 C 程序中强制转换 malloc 的返回值。

标签: c function pointers structure


【解决方案1】:

线

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

是错误的 - 它在初始化之前使用 newImg-&gt;xnewImg-&gt;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-&gt;data你分配给)

【讨论】:

  • 谢谢,这似乎解决了一些问题,但现在生成的图像是黑色矩形,而不是旋转图像。你知道是什么原因造成的吗?
  • @DavidRC 我已经更新了我的答案,并记录了您代码中的另一个错误。循环循环正在更新img 的内容,而不是写入newImg
  • 抱歉,当您花费数小时摆弄同一段代码时,您会忘记发布的版本。奇怪的是,现在我得到了随机噪声作为图像。我将修改我使用的算法(我试图远离数组)。
【解决方案2】:

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

这里你没有初始化你的变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2015-01-13
    • 2018-05-27
    • 2013-06-13
    • 1970-01-01
    • 2015-06-16
    • 2018-08-06
    相关资源
    最近更新 更多