| Mary90 (2) | |
|
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
|
|
| SuperSonic (64) | |||||
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:
This will create a 2d array like you want. You're final function should look like this:
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
|
|||||
| SuperSonic (64) | |
| I hope I explained it well. Please tell me if you don't understand it. | |
|
|
|
| Mary90 (2) | |
| 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. | |
|
|
|
| SuperSonic (64) | |
| Glad I could help! | |
|
|
|