Problem using flattened array (i get output in hex trying to print 2D array like 1D array - row major order)

I read the input from file and print it using 2 indices [i][j] but when i try to print using 1 index for linear array, i get wrong output. The file looks like this(numbers separated by tabs):

90 89 73
90 43 25
74 19 41
49 24 54
96 41 87
..................

Can someone tell me why is this happening?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
float** read_file(std::string filename, int rows, int cols)
{
	std::fstream file;
	file.open(filename.c_str(), std::ios::in);
	if (!file.is_open()){ return 0; }

	float** floats = new float*[rows];
	for (int i = 0; i <rows; i++){ floats[i] = new float[cols]; }

	//read each row
	for (int i = 0; i<rows; i++)
	{
		for (int j = 0; j<cols; j++)
		{
			file >> floats[i][j];
		}
	}
	file.close();

	return floats;
}

int main()
{
	int rows = 10;
	int cols = 3;
	//float** floats = (float**)malloc(sizeof(float*)*rows*cols);
	if (!(floats = read_file("test.txt", rows, cols))){ return 0; }
	
	//write out the data
	for (int i = 0; i<rows; ++i)
	{
		for (int j = 0; j<cols; ++j)
                { std::cout << floats[i][j] << "\t"; }
		std::cout << "\n";
	}
	
	
	for (int i = 0; i<rows; ++i)
	{
		for (int j = 0; j<cols; ++j)
                 { std::cout << floats[i*cols+j] << "\t"; }
		std::cout << "\n";
	}
	
	char wait;
	std::cin >> wait;

	free(floats);
	return 0;
}



Last edited on
Please, use code tags: http://www.cplusplus.com/articles/jEywvCM9/

The problem:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
float** floats = new float*[rows];
// floats is an array that contains 'rows' pointers
// floats[i] is a pointer
for (int i = 0; i <rows; ++i)
{
  floats[i] = new float[cols];
}

for (int i = 0; i<rows; ++i)
{
  for (int j = 0; j<cols; ++j)
  {
    int index = i*cols+j;
    std::cout << floats[index] << "\t";  // you print pointers
    // printing a pointer shows the address (as hex value)

    // furthermore, index is not just in range [0..rows[, but in much larger [0..rows*cols[
  }
  std::cout << "\n";
}

Besides, you do not have a continuous block for the data; you have a separate block for each row.

PS. This is an error too:
1
2
float** floats = new float*[rows];
free(floats);
Thank you for your answer. How can I print the values, not pointers?
You dereference the pointer. That returns the value from the memory address that the pointer holds.

However, you should have your data in continuous memory block, if you want to access all of it like a 1D array.
Topic archived. No new replies allowed.