开发者

Referencing elements from two-dimensional array with a single value

开发者 https://www.devze.com 2023-02-14 15:06 出处:网络
I am probably missing something fundamental, but i cannot find a solution to the following issue. I have a two-dimensional array of some float elements and i am trying to find a way to be able to refe

I am probably missing something fundamental, but i cannot find a solution to the following issue. I have a two-dimensional array of some float elements and i am trying to find a way to be able to reference them by using only a single value. Example:

float test[5][50];
test[3][25] = 34.67;
cout << test[3][25] << endl;
int id = 25;
cout << *test[id*5+3] << endl;

I am hoping to get same result from both cout. Instead my output looks like this:

34.67
Segmentation fault

W开发者_如何学编程hat am I doing wrong?

Thanks!


Without testing, I think something like this might work. Note that C++ arrays are major->minor from left dimension to right dimension.

float test[5][50];
test[3][25] = 34.67;
cout << test[3][25] << endl;
int id = 25;
float* test2 = &test[0][0]
cout << test2[(3 * 50) + id] << endl;


test is a float[][] with 5 elements (each of which is a float[] with 50 elements), and you are referring to test[128]. Hence the seg fault.You need to convert from single index to subscript using integer division and mod:

cout << test[id/50][id%50] << endl;

You should assert(id/50<5); to make sure your index is within bounds.


The crash is because you are trying to read the contents of the element as a memory address

*test[id*5+3] means int address = test[id*5+3]; then read memory at address.
If that address is 0 or memory you don't own then it will crash.


Accessing a two-dimensional bitmap (image) with a single reference is often useful.

Use:

int image2D[dim2][dim1];
int *image1D = &image2D[0][0];

Now

image2D[i][j] == image1d[i*dim1+j]


I agree with the first comment, that you really shouldn't do it, but I'll answer anyway.

I think that if you try:

cout << test[id*5+3] << endl;

it should work. There is no need to dereference with *.

0

精彩评论

暂无评论...
验证码 换一张
取 消