I'm trying to write a function which generates and returns an array. I know I can't actually return the array and instead need to return a pointer, but I'm still confused about how pointers work. What I've done is the following:
adj is a 2D array, so it's an int**.
But it will go out of scope at the end of the function so you won't be able to return it unless you allocate it dynamically ( which you will need to do anyway since it size depends on an argument )
Try; a = reinterpret_cast<int *>(adj);
This will only help you to prevent this compiler error , but as Bazzy said, you shall allocate memory dynamically to make your function work.
int** gen_graph(int n, float p)
{
srand (time (NULL));
int ** adj;
adj = newint[n][n];
int i = 0;
while (i < n)
{
adj[i][i] = 0;
int j = i + 1;
while (j < n)
{
int A = rand();
float B = A/RAND_MAX;
if (B < p)
{
adj[i][j] = 1;
}
else{
adj[i][j] = 0;
}
adj[j][i] = adj[i][j];
j++;
}
i++;
}
int **a;
a = adj;
return a;
}
Thanks for those links. I'm afraid I'm still confused -- let me see if I can articulate why:
In the example given towards the bottom of http://www.cplusplus.com/doc/tutorial/dynamic/ , the value in the new statement is a variable value entered by the user (i), not a constant value. However, in my program, even when I modify it based on this example to prompt the user to input n instead of declaring n as an argument, and then say adj = new int[n][n]; , I get the error "n cannot appear in a constant-expression".
I'm not convinced that the function in question needs to actually construct the array. I would encourage you to do a couple of things. b will alleviate some of your concerns with regards to how to return the array while a allows you to make the array without worrying about operator new or delete.
a) use sequence containers such as std::vector.
b) create the object within the caller and simply pass a reference to the gen_graph function.