Array Help

I was wondering if there was a way to transfer the values of an array created in a function to an array in a different area of the program. I know this probably unclear.

i.e.

#include <iostream>

using namespace std;

int array(int x, int y) {
int num[2];
num[0] = x;
num[1] = y;
return num[];
/*I was wondering if it were possible to transfer this array down to the int main() when the function was called. */
}

int main() {
int a=3;
int b=2;
int nums[2]; /*how would one transfer the values of the num[] array from the function array() to the array nums[]. */
}
Last edited on
You can pass a pointer to the first element in the array and have the function set the elements in the array.

1
2
3
4
5
6
7
8
9
void array(int x, int y, int* num) {
	num[0] = x;
	num[1] = y;
}

int main() {
	int nums[2];
	array(10, 100, nums);
}
Note that there is an entity in the std namespace called "array", so using namespace std; isn't advised here, if you're going to use "array" as a name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

void set_array( int* a, int x, int y )
{
    a[0] = x ;
    a[1] = y ;
}

int main()
{
    int nums[2] ;
    int a=3, b=2 ;

    set_array(nums, a, b) ;
 
    std::cout << nums[0] << ", " << nums[1] << '\n' ;
}


Ok thanks; thats useful. Also, is it possible to test if two arrays are equal to each other. Like:

int num [] = {1,2,3};

int order [] = {1,3,2};

is it possible to easily test whether these two arrays are equivalent.
closed account (D80DSL3A)
I suppose 1st compare the sizes. If the sizes match then proceed to an element by element comparison.

1
2
3
4
5
6
7
bool are_equal( int A[], unsigned szA, int B[], unsigned szB )
{
    if( szA != szB ) return false;// A, B can't be equal
    for(unsigned i = 0; i < szA; ++i )
        if( A[i] != B[i] ) return false;// once is all it takes
    return true;
}
Last edited on
If you could use vectors or at least the C++ arrays cire mentioned, it would be simpler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <array>

std::array<int, 2> array(int x, int y) {
    std::array<int, 2> result = {x, y};
    return result;
}

int main()
{
    std::array<int, 2> order = {1,2};
    std::array<int, 2> nums = array(1, 2);
    if(nums == order)
        std::cout << "The arrays are equal\n";
}

demo: http://ideone.com/7LdZAA
Last edited on
Topic archived. No new replies allowed.