Need help with Array problem.

I am trying to write a program where the user inputs the length of the array. Then based on that length, the user is asked to input the elements for several different array. Then print both of the arrays one after the other. I am lost on what to do next or what I am doing wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;
int array1(int a[], int n);
int array2(int b[], int n);
int main(){
    int a[]={};
    int b[]={};
    int n;
    cout << "Enter the length of the array:" << endl;
    cin >> n;
    array1(a,n);
    array2(b,n);
    cout << a[0] << a[1] << a[2] << a[3] << endl;
    cout << b[0] << b[1] << b[2] << b[3] << endl;
return 0;
}

int array1(int a[], int n){
    int x;
    cout << "Enter the element of array a." << endl;
    for (int i=0; i < n; i++){
    cin >> a[i];
    }
return 0;
}

int array2(int b[], int n){
    int y;
    cout << "Enter the elements of array b." << endl;
    for (int j=0; j < n; j++){
    cin >> b[j];
    }
return 0;
}


The way I approached is by first asking the length of the array "n" in the main function. Next I created function array1 and array2 which asks the user to input elements of array with range n using for loop. Then on the main I call these functions. The problem I am having is that when I call array1 and array2 then asks to print the elements of array1 and array2, I get the elements from array2 for both array1 and array2.


1
2
int a[]={};
int b[]={};

This creates two arrays of zero length so they are not very useful. Not even sure it's valid C++.

Do you know how to dynamically allocate an array? It would allow you to create arrays who's length is decided at runtime.
Thank you for answering. I just searched dynamically allocating an array and read what it does in general. I have not read about it in class so far.

I now understand what it does. Thanks for pointing it out. Going to test it out and how it works.
Last edited on
Topic archived. No new replies allowed.