Please help me to remove the error

So, I am supposed to write a code for matrix addition by two dimensional float arrays. The code is supposed to ask the user to enter the dimensions of matrix A (m by n) and matrix B(p by q), given that I initialized the matrices by the function member (not sure if that is what it is called) "rand()%10", but when I try compiling it, gives me the following errors "array bound is not an integer constant before ‘]’ token" "expected ‘)’ before ‘,’ token" and "expected unqualified-id before ‘float’", all in line 6, and I really have no idea as to how I am supposed to fix the errors. So please help.

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
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int m, n, p, q;
float matrixAddition (float A[][n], float B[][q])
{
	if ((m==p) && (n==q))
	{
		for (int i = 0; i < m || i < p; i++)
		{
			for (int j = 0; j < n || j < q; j++)
			{
				float C[m][n] = A[m][n]+B[p][q];
			}
		}
		return (C[m][n]);
	}
	else
	{
		cout << "Dimensions of matrix don't match! \n";
	}
}
int main (void)
{
	cout << "Enter dimensions m by n of matrix A: ";
	cin >> m >> n;
	cout << "Enter dimensions p by q of matrix B: ";
	cin >> p >> q;
	
	const float matrixA [m][n] = rand()%10;
	const float matrixB [p][q] = rand()%10;
	string operation;
	
	cout << "What operation do you wish to carry out? \n";
	cout << "additon? subtraction? multiplication? or transpose? \n";
	
	if (operation == "addition")
	{
		matrixAdditon(matrixA, matrixB)
	}
	return (0);
}
When defining an array, you must use constant integers for the dimensions. m, n, p and q are not constant.
If what you mean is use "const" in front of my "int m,n,p,q", then it doesn't work, it says that they are not initialized
I wasn't suggesting a solution, I was explaining the problem and why it was occurring.

If you want to have arrays of a size that isn't known at run-time, the best solution is to use vectors instead.

If you absolutely insist on using C-style arrays, you'll need to dynamically allocate memory for the arrays after you know what size they need to be.
Do you know how to use dynamic memory allocation?
Line 31, 32: You can't allocate an array like that in C++. In C++, the compiler must know the size of the array at compile time. Also, you initialization of the arrays is not valid. As freddy92 implied, you need to allocate variable sized arrays using new or use std::vector.

Why are m,n,p,q global? They should be local to main.

Topic archived. No new replies allowed.