PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] How do i pass an array of structs by reference to a function?

 July 06, 2022     arrays, c, pass-by-reference, struct, swap     No comments   

Issue

I need to write a function that would reflect an image by having ever pixel in the image with in a 2D array of structs. Below is the function i have written which basically switches the last pixel with the first pixel and so on but i need it to edit the original array and not a copy which is what its currently not doing. Below is the function within main and how the function is laid out. Any input would help!

reflect(height, width, &image);

Function:

void reflect(int height, int width, RGBTRIPLE *image[height][width])
{
    RGBTRIPLE temp;
    for ( int i = 0 ; i < height ; i++)
    {
        for( int j = 0 ; j < width ; j++)
        {
            temp = image[i][j];
            image[i][j] = image[i][width-j-1];
            image[i][width-1-j]=temp;

        }
    }
}

And the struct is as shown below

typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

The array of structs is created using this:

    // Allocate memory for image
    RGBTRIPLE(*image)[width] = calloc(height, width * sizeof(RGBTRIPLE));

Solution

For starters the function should be declared either like

void reflect(int height, int width, RGBTRIPLE image[height][width]);

or like

void reflect(int height, int width, RGBTRIPLE image[][width]);

or like

void reflect(int height, int width, RGBTRIPLE ( *image )[width]);

and called like

reflect(height, width, image);

Within the function the loop should look like

for ( int i = 0 ; i < height ; i++)
{
    for( int j = 0 ; j < width / 2 ; j++)
    {
        temp = image[i][j];
        image[i][j] = image[i][width-j-1];
        image[i][width-1-j]=temp;

    }
}


Answered By - Vlad from Moscow
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing