How to declare a function?

Hi,

first of all, I'm beginner. Sorry for the stupid looking question.


I want to split my codes so I want to call a function:

I have a int main() and I want to call a function, which creates a Matrix size LxL. The parameters given are L and p (probability). How do I have to call the function in main() and how do I declare the function ????? lattice? The return value is a matrix.



???? lattice(int L, double p) {

int N[L][L];
for (int i=0; i<L; i++) {
for (int j=0; j<L; j++) {

if (rand()%100<p*100){
N[i][j] = 0;
}
else {
N[i][j] = 1;
}
}
return N;
}


Last edited on
I may be wrong, but I think this is how you'd have to do it. First of all, when you want to return an array, you must declare your function as a pointer, and if it's a two dimmensional array, you must declare it as a pointer to a pointer. That might be confusing, but stay with me. Your function header should look like this:
int **lattice(int L, double p)
Now I noticed that you are trying to declare your N variable as a normal 2d array, but you're using L to define its size. This won't work. You must use a constant size to define an array, but if you want a variable size, you can use a pointer and allocate it dynamically like this:
1
2
3
4
5
int **N = new int*[L];
for(int i = 0; i < L; i++)
{
    N[i] = new int[L];
}

This will create a 2d array like you want. You're final function should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int **lattice(int L, double p)
{
    int **N = new int*[L];
    for(int i = 0; i < L; i++)
    {
        N[i] = new int[L];
    }
    for (int i=0; i<L; i++)
    {
        for (int j=0; j<L; j++)
        {
            if (rand()%100<p*100)
            {
                N[i][j] = 0;
            }
            else
            {
                N[i][j] = 1;
            }
        }
    }
    return N;
}

I haven't tested this code yet, so it might not work. Just let me know if it doesn't.

*edit* I tested it. It works fine. I hope that helps :)
**edit** To make an array that will work with this function, you must declare it like this:
int **x = lattice(5, 0.5);
Last edited on
I hope I explained it well. Please tell me if you don't understand it.
Thank you. It works but I have to learn myself, why it's working. ;-) Maybe I have some questions and I will ask you later. Thank you.
Glad I could help!
Topic archived. No new replies allowed.