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

2019-08-26 19:46发布

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?

4条回答
叼着烟拽天下
2楼-- · 2019-08-26 20:19

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.

查看更多
SAY GOODBYE
3楼-- · 2019-08-26 20:25

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;

查看更多
贼婆χ
4楼-- · 2019-08-26 20:30

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.

查看更多
我命由我不由天
5楼-- · 2019-08-26 20:36

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.

查看更多
登录 后发表回答