Declaring a 2D array of type struct in c++ [closed

2019-08-26 19:36发布

问题:

I declared a struct which is supposed to be a pixel and it has 3 properties (x, y location and F intensity) like this:

struct pixel {
    int F,          // intensity from 0-255
    x,              // horizontal component           
    y;              // vertical component
};

Then I declared an 2D array of type pixel (the struct above) like this:

int N=100;
pixel image[N][N];

Then I used the following loop to assign values to x and y:

int count, k;

for (int i=0 ; i<N ; i++)
    for (int j=0 ; j<N ; j++)
    {
        k = j + i*N;
        image.x[k] = count;
        count++; 
     }

What did I do wrong?

回答1:

The line

image.x[k] = count;

is incorrect. You declared a 2D array of pixels:

pixel image[N][N];

The way to access an element of the array is as follows:

image[i][j].x = count;

You do not need to calculate the flat index k yourself.



回答2:

You can use i and j to index into image:

    image[i][j].x = count;

I don't see why you'd need k and the explicit index calculation at all. The compiler will do it for you automatically.



回答3:

You are trying to index a field of the struct rather than the struct itself, plus you are not indexing it as a 2D array.

Rather than doing:

image.x[k]

Do:

image[i][j].x

Also, does your code compile? Some compilers will reject an declaration of an array where the bounds are variables, even if const.



回答4:

First of all, 'k' is not defined. So, it will use a garbage value for k.

Also, for indexing of a point in an image, you have to use:

image[i][j]

So, the correction in your program will be:

image[i][j].x = count;

instead of image.x[k] = count;