Why my program keeps giving me garbage at the same spot

Can someone help me check my program? I create a 1D dynamic array to emulate a 2D array and returns a pointer to the 1D dynamic array but some garbage always appeared at the position I highlighted.

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
using namespace std;
int* create2Darray(int rows, int columns);
void set(int *arr, int rows, int columns, int desired_row, int desired_column, int val);
int get(int *arr, int rows, int columns, int desired_row, int desired_column);
int main()
{

    int *arr = create2Darray(10,10);

    for (int i = 0; i < 10; i ++)
    {
        for(int j = 0; j < 10; j ++)
        {
            set(arr, 10, 10, i, j, i*10+j);
        }
    }
    for (int i = 0; i < 10; i ++)
    {
        for(int j = 0; j < 10; j ++)
        {
			if(i == 0 && j == 9)
				cout <<"[0][9]=";//here is the position of the garbage
            cout << get(arr, 10, 10, i, j) << " ";
			
        }
		cout << endl;
    }
    set(arr, 10, 10, 10, 10, 10);
    get(arr, 10, 10, 10, 10);
    return 0;





}

int* create2Darray(int rows, int columns)
{
    return new int(rows * columns);
}

void set(int *arr, int rows, int columns, int desired_row, int desired_column, int val)
{
    if (desired_row<rows&&desired_column<columns&&desired_row>=0&&desired_column>=0)
    {
        arr[desired_row*columns+desired_column] = val;
    }

    else
    {
        cout << "Invalid index!" << endl;
        return;
    }
}

int get(int *arr, int rows, int columns, int desired_row, int desired_column)
{
    if (desired_row<rows&&desired_column<columns&&desired_row>=0&&desired_column>=0)
    {
        return arr[desired_row*columns+desired_column];
    }

    else
    {
        cout << "Invalid index!" << endl;
        system("pause");
        exit(0);
    }
}

Last edited on
I can't confirm: https://ideone.com/XXKTxW

Note that you are leaking memory because you never free the array. Why not use a std::vector instead?
Could you tell me how to fix this memory leaks?
closed account (E0p9LyTq)
If you have to use a fixed size array you could use the new C++11 STL array container. With variable sized array you can use vector.

The STL containers maintain their memory internally, no memory leaks.

http://www.cplusplus.com/reference/array/array/
http://www.cplusplus.com/reference/vector/vector/
The create2Darray function allocates one int that is initialized to the value of rows * columns.
Ah, @Peter87 is right - the subtle difference between round parentheses and square brackets makes a huge difference. It would have taken me a while to spot that - that sort of problem doesn't happen with a standard library container.
Last edited on
Topic archived. No new replies allowed.