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

落爺英雄遲暮 提交于 2020-01-16 14:45:15

问题


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;



来源:https://stackoverflow.com/questions/13847980/declaring-a-2d-array-of-type-struct-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!