Passing 2D array to a function

What's wrong with this?
I'm gonna take row&column and matrix numbers from input and print out the 2D matrix.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
using namespace std;

	int c,r;
void matnums(int c, int r, double **x){
	int arr;
	for(int i=0;i<c;i++){
		for(int j=0;j<r;j++){
			arr = x[i][j];
			cout << arr << '\n';
		}
	}
}


int main(){
	int c, r;
	double** x;
	cout << "Type column and row: ";
	cin >> c >> r;
	cout << "Type matrix numbers: ";
	matnums(c,r,x);
	return 0;
}
mhz wrote:
What's wrong with this?
Why do you expect us to know? We can tell you how to fix problems but we can't read your mind to know what those problems are.
I mean was how can I fix it?! Problem is compiler hanged and stopped working.
Last edited on
closed account (E0p9LyTq)
How can we help you to fix it when you won't tell us what is wrong? Are you getting compiler errors? Are you getting unexpected runtime output?
You can run it here to make sense what I'm saying. I suppose it because of calling x array in main function.
You never assign x to point to anything, so it just points at random memory. Then you try to read from that random memory. I don't know what you expected to happen; it's undefined behavior.
Last edited on
Thanks LB, Sounds like true. actually I'm new. Can you tell me what should I do?
Well, I don't know what you want your program to do. Are you trying to have the user fill in the array values? It is hard to tell from your code.
yes.as I said user fill row and column number also matrix numbers(array numbers). Isn't my question clear?
Well, after you get the dimensions from the user, you need to actually allocate the array. You can either use a 1D array and use math to treat it as a 2D array, or you can use an array of arrays which takes more work but might be easier to think about. Remember you also have to free the memory when you're done with it.
Last edited on
Topic archived. No new replies allowed.