Link to elements from a two-dimensional array with a single value

I probably have something missing, but I can’t find a solution to the following problem. I have a two-dimensional array of some float elements, and I'm trying to find a way to reference them using only one 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 hope to get the same result from both cout. Instead, my output is as follows:

34.67
Segmentation fault

What am I doing wrong?

Thank!

+3
source share
5 answers

Without testing, I think something like this might work. Please note that C ++ arrays are primary -> secondary from measurement from left to size.

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;
+5
source

The accident occurs because you are trying to read the contents of an element as a memory address

*test[id*5+3] int address = test[id*5+3];, .
0 , , .

+2

test - float[][] 5 ( float[] 50 ), test[128]. , seg fault.You mod:

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

assert(id/50<5); , .

+2

() .

:

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

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

, , .

, :

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

. *.

0

Source: https://habr.com/ru/post/1795787/


All Articles