Dear I am trying to send a dynamic array as a parameter to a function in C++ but it tells me as an error that the variable N is out of context or is not defined, how can I solve this error? Stay tuned. Greetings.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void generarArreglo(int matriz[n][n]){
srand(time(NULL));
for(int i=0;i<=6;i++){
for(int j=0;j<=6;j++){
matriz[i][j]=rand()%99+1;
}
}
}
void imprimirArreglo(int matriz[n][n]){
for(int i=0;i<=6;i++){
for(int j=0;j<=6;j++){
cout<<matriz[i][j]<<"\t";
}
cout<<endl;
}
}
int main(){
int n;
cin >> n;
int matriz[n][n];
generarArreglo(matriz);
imprimirArreglo(matriz);
system("pause");
return 0;
}
My solution:
Entry:
Departure:
The error is occurring here:
And the reason is that
n
it does not exist for those functions. If it were a constant value known at compile time you could patch the code such that:But is not the case. As you have already been proposed a solution using an array based on double pointers, I propose a similar solution with simple pointers... or with a single vector. The advantage of using STL containers is that you avoid dealing with heap memory, which is usually a big relief:
And the same could be achieved with a single pointer... the advantages over a double pointer are basically two:
Example with simple pointer:
Your code
is not valid in C++. The dimensions of an array must be constants, not variables. You'll have to declare it as a pointer, and allocate memory on the fly:
And you will have to modify all your functions, of course.
EDIT
To access via pointers, it's the same (I'm sure in C, throw me to the wolves if the same doesn't happen in C++):
If instead of ugly and dirty C++ you used plain C , you could use variables to declare arrays (in C11).
In C , a
array
and apuntero
are equivalent. If you declare aarray[]
, the compiler allocates memory for the indicated size, and what you actually use is a pointer to that memory.EDIT 2
Why do you use 2
for
nested ? with what do you useThe
array
and memory blocks returned bycalloc()
,malloc()
and the like are contiguous in memory . Simply, imagine that it is aarray[]
one-dimensional, but much longer.EDIT 3
From your comments, I see you wanting to learn.
Version 1.0. Patches are supported.
PS - For code like that, C / C++ are said to be write-only .
I propose that the array be declared in the form:
Only as a good practice, because if it is declared dynamically, although this is done automatically, it is recommended that in the end the memory that was requested from the system be manually released, however, in this way, it is not necessary. The other thing I propose is that by passing the array as a parameter as a pointer + the dimensions, this makes it much more flexible when working with the array if we want to make subsequent changes to its dimensions.