simple arrayproblem

Hello people, im new on this forum, and also new to programming.
I have a problem i have spent some hours trying to figure out, but i cant seem to get it.

I have written this code to illustrate my problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include <iostream>
using namespace std;


void test();

int main(){
  //calling my function
  test();
  
  //declearing my array from test()
  int x[2];

  //i use cout to check if i really have a copy of x[] 
  cout << x[0] << x[1];

  //output: i have obviously not
  
void test(){
  int x[2] = {1,2};
}




Comment:
This just illustrates my problem. What im actually working on is this:
i have created a function which generates an array of size 4, with 4 random letters in. I.e. array1[4] ={A B B F}
I have also created a function which allow input so that one can guess which letters are generated. I.e. array2[4] = {A B C D}
And then i have to TRANSFER these arrays over in a third function so that i can check how many letters are guessed correctly. In this case the answer is 2.

So: how can i use an array generated in functionA, in functionB ?

Thank you very much for your help.

-cid
Last edited on
The scope of variables is limited to the function in which it is defined. Here your array is defined in function test() and it gets destroyed when the function returns. You will have to declare the array in main function, pass the pointer to that array to test(), so the changes done to that array by test(), are reflected in your main function.
Thanks for quick reply.
Is this the only way? I have not been learning about pointers yet. Maybe you can give me a quick example on the use of pointers in this context?

-cid
1
2
3
4
5
6
7
int x[2];
test(x);
//...
void test(int *x){
    x[0]=1;
    x[1]=2;
}
Last edited on
test(int* arr)
{
arr[0] = 99;
arr[1] = 99;
}

int main()
{
int arr[2]; //initialize it to 0

test(int* arr);

cout <<arr[0] << arr[1] << endl; //this will print 99

return 0;
}
It would've been great if someone could explain the code for me. All i see is a star that magically solves the problem..
You will need to do some basics on pointers to get that. But the essence is "an array can be represented by a pointer".
Ok, thanks!
But i think its possible to pass the array as a reference, or something.. Can this be?
Yes but using pointers is easier
1
2
3
4
5
6
7
8
9
10
11
12
//by reference
void test( int (&x)[2] )
{
	x[0] = 1;
	x[1] = 2;
}
//by pointer
void test( int *x )
{
	x[0] = 1;
	x[1] = 2;
}
Hmm... I'm questioning the validity of that syntax... Too bad right now I don't have a compiler to try it out.
But my problem is to use an array (say array1) that one function (say function1) has created, in another function (say function2) who changes that array (array1).
I cant get this to work since i cant return an array from function1.
The code both n4nature and I posted does exactly what you described.
Topic archived. No new replies allowed.