c++ 2D dynamic array defaulting to size 4

Hi. Below is my c++ code. I am trying to create a 2D dynamic array which is created with the correct number of rows and columns. However, I can't seem to access row and column values above 4. Even sizeof(array) and sizeof(array[0]) both output 4.


1
2
3
4
5
6
7
8
9
10
11
12
int x;
int y = 5;
float** g_schedule;

int main(){
   x = findSize();

   g_schedule = new float* [x];
   for (int row = 0;row < x;row++){
	g_schedule[row] = new float[y];
   } 
}
closed account (48T7M4Gy)
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
#include <iostream>

int main()
{
    int x = 7;  // number of rows
    int y = 5; // number of columns
    
    // Create matrix
    int** g_schedule = new int*[x];
    for(int i = 0; i < x; ++i)
        g_schedule[i] = new int[y];
        
    // Generate values
    for(int i = 0; i < x; i++)
    {
        for(int j = 0; j < y; j++)
            g_schedule[i][j] = (i +j) * (i * j);
    }
    
    // Display matrix 
    for(int i = 0; i < x; i++)
    {
        for(int j = 0; j < y; j++)
            std::cout << g_schedule[i][j] << '\t';
        std::cout << '\n';
    }
    
    // Display "size"
    std::cout << "Size (ie no. of elements): " << x * y << '\n';
}
0	0	0	0	0	
0	2	6	12	20	
0	6	16	30	48	
0	12	30	54	84	
0	20	48	84	128	
0	30	70	120	180	
0	42	96	162	240	
Size (ie no. of elements): 35


http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new
Last edited on
g_schedule is a pointer so sizeof(g_schedule) will give you the size of a pointer.
g_schedule[0] is also a pointer so sizeof(g_schedule[0]) will also give you the size of a pointer.
To know the size you need to keep track of it using variables.
closed account (48T7M4Gy)
The size, in the conventional sense of a 2-d array, is already given by the 2 variables x and y.

sizeof(int) = 4 may be more than a coincidence.

Maybe the fact that OP hasn't initialised x is a factor too.

But despite all of this, we haven't seen what findSize() does.
Thank you Peter87 and kemort, works perfectly now. The example also made it that much more easier to test. I found it awkward that 4 was always the output, but did not interrogate my code further.
Topic archived. No new replies allowed.