A.A.Smiles A.A.Smiles - 16 days ago 5
C++ Question

Use 2D array in a function C++

I need to use a square 2D array (arr[n][n]) in a C++ void function that creates a latin square but the requirement is that the size of n is not given at the start of program. The user has to input the size of array. Example of my code (that is failing):

int n;
void arrayz(int n , int arr[][])
{
for (int i = 0; i < n; i++)
{
for (int k = 0; k < n; k++)
{
for (int e = 1; e <= n; e++)
{
arr[i][k] = e;
}
}
}
}
int main()
{
int arr[n][n];
cin >> n;
void arrayz (n, arr[n][n])
}


Please help me with this problem!

Answer

There are several problems with your code, and it's unclear if you're just trying to get your work done for you, so I'll try a pedagogical approach:

  1. As stated, if you want the array size to be user input, that is dynamically allocate, you need the malloc function. Than your arr variable is defined as a int**, and then you allocate space for it.

  2. When calling a function you don't write the return type (void in last line)

  3. When sending an array c style, just send the address - the array name in this case (arr, no [][]).

  4. When defining a multidimensional array as a function argument, you must submit the first size at least. You don't know it though, since the user gives it, so just accept the pointer (int** for example).

I suggest googling a C tutorial if it isn't clear to you how to make these adjustments.

Comments