当我返回一个多维数组时,如何将函数中的内容传递回我的结构

时间:2013-12-08 02:47:48

标签: c function multidimensional-array struct

我有两个结构和一个函数。我希望能够将函数中的表达式传递回主程序。但它是一个多维数组...因为我试图打印出来......

//Setting the struct up for the pixel's
struct pixel
{
   unsigned char red;
   unsigned char green;
   unsigned char blue;
};

//Setting the struct up for the Image Type and scanning in the pixels into an array
struct ImageType
{
   char ppImage[3];
   char comment[256];
   char newlinechar;
   int width, height;
   int maxColor;
   struct pixel image[256][256];
};

我的功能

//Function in order to flip the image, going from the left most pixel flipping with the    right most
void MirrorVertical(struct ImageType imgur)
{
   int x, y;

   for(x=0; x < imgur.width; x++)
      {
         for(y=0; y < imgur.height; y++)
            {
               imgur.image[x][y]=imgur.image[(imgur.width*imgur.width)-x-1][y];
            }
      }
}

@nhgrif我原来是这样的

    for(x=0; x < imgur.width; x++)
      {
         for(y=0; y < imgur.height/2; y++)
            {
               temp = imgur.image[x][y];
               imgur.image[x][y] = imgur.image[x][imgur.height-y-1];
               imgur.image[x][imgur.height-y-1] = temp;
            }
      }
}

其中temp被定义为struct pixel temp;作为一个举办它的地方。

1 个答案:

答案 0 :(得分:1)

为什么不使用指针?

//Function in order to flip the image, going from the left most pixel
// flipping with the right most
void MirrorVertical(struct ImageType *imgur)
{
  int x, y;
  for (x = 0; x < imgur->width; x++) {
    for(y = 0; y < imgur->height; y++) {
      imgur->image[x][y] = imgur->image[(imgur->width * imgur->width)-x-1][y];
    }
  }
}

MirrorVertical(&img);

编辑:

这假设您正在尝试修改原始结构。

更多编辑:

此版本创建像素阵列的镜像副本,使原始对象保持不变。

// Function in order to flip the image, going from the left most pixel
// flipping with the right most
void MirrorVertical(struct ImageType imgur, struct pixel (*mirror)[256])
{
  int x, y1, y2;
  for (x = 0; x < imgur.width; x++)
    for (y1 = imgur.height-1, y2 = 0; y1 >= 0; y1--, y2++)
      mirror[x][y2] = imgur.image[x][y1];
}

struct pixel mirror[256][256];
MirrorVertical(imgur, mirror);

/* use mirror[x][y].red, ... */