How to place a two-dimensional matrix, without defined size in a struct in C, and access the elements of this matrix by the struct itself?

Asked

Viewed 103 times

0

I’m a beginner in C, and I’m having a bit of a problem with matrices and structs and pointers. My question is a little confusing to understand, but come on. I have two typedef, to define two types of data for a project I’m doing. Here they are below:

typedef struct pixel {
    int red, green, blue;
} PIXEL;

typedef struct image {
    int width, height;
    PIXEL pixels[IMAGE.width][IMAGE.height];
} IMAGE;

However, I am confused to define the last element of the type, which should be a element matrix of the kind PIXEL. As I do not know how many elements my matrix will have, I thought it would be right to put the attributes of height and width within the definition of my matrix, but I did not succeed.

My goal is to get this matrix inside the type IMAGE and be able to access it as follows:

for (int i = 0; i < image.width; i++){
    for (int j = 0; j < image.height; j++){
        printf("|%d, %d, %d", image.pixels[i][j].red, image.pixels[i][j].green, image.pixels[i][j].blue);
    }
    printf("|");
}

This should result in accessing the matrix elements created within image, and how each element is of type PIXEL, and has the attributes red, green, blue, also be able to access them.

I also saw that it is possible to use a pointer to the matrix inside the struct, so that the type would look like this:

typedef struct image {
    int width, height;
    PIXEL *pixels;
} IMAGE;

However, I don’t know how to work with this structure. I come from Python, and in it we don’t have pointers and structs, so I get a little confused by all this.

I would be extremely grateful if you could help me think of a solution to this problem.

1 answer

0


Because vectors are static, the compiler must know their size at compile time. If the size will only be set at runtime, the vector must be dynamically allocated.

Example of a function that allocates a matrix (which is also a vector, but two-dimensional) dynamically:

typedef struct image {
    int width, height;
    PIXEL** pixels;      // repare nos dois '*', para indicar que que é uma matriz
} IMAGE;


IMAGE make_image(int width, int height)
{
    IMAGE img;

    img.pixels = malloc(sizeof(PIXEL*) * height);

    for(int i = 0; i < height; i++)
    {
        img.pixels[i] = malloc(sizeof(PIXEL) * width);
    }
    img.width  = width;
    img.height = height;
    return img;
}

The above function creates a size image widthxheight.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.