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?
You can use
i
andj
to index intoimage
:I don't see why you'd need
k
and the explicit index calculation at all. The compiler will do it for you automatically.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:
So, the correction in your program will be:
instead of
image.x[k] = count;
The line
is incorrect. You declared a 2D array of pixels:
The way to access an element of the array is as follows:
You do not need to calculate the flat index k yourself.
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:
Do:
Also, does your code compile? Some compilers will reject an declaration of an array where the bounds are variables, even if const.