How to pass arrays in the main func. w/ c++

2019-03-07 00:32发布

问题:

#include <iostream>

using namespace std;

const int MAX = 1000;
int  ArrMix[MAX];
int *ptrArrPos[MAX];
int *ptrArrNeg[MAX];
int PosCounter = 0;
int NegCounter = 0;
int r;


void accept(int ArrMix[MAX])
{
    cout<<"Enter the number of elements in your array: ";
    cin>>r;

    for (int i = 0; i < r; i++)
    {
        cout<<"Enter value:";
        cin>>ArrMix[i];
    }
}

void process(int &i)
{
    if(ArrMix[i] >= 0)
    {
        ptrArrPos[PosCounter] = &ArrMix[i];
        PosCounter++;
    }
    else
    {
        ptrArrNeg[NegCounter] = &ArrMix[i];
        NegCounter++;
    }
}

void display(int &i)
{
    cout<<"Your passed array is: " << endl; 
    cout<<ArrMix[i] << endl;
    cout <<"Total number of positive integers is: "<<PosCounter<<endl;
    cout<<"Your positive array is: "<<endl;
    for (int i = 0; i < PosCounter; i++)
    {
        cout << *ptrArrPos[i] << endl;
    }  
    cout<<endl;
    cout <<"Total number of Negative integers is: "<<NegCounter<<endl;
    cout<<"Your negative array is: "<<endl;
    for (int i = 0; i < NegCounter; i++)
    {
    cout << *ptrArrNeg[i] << endl;
    }
}

int main ()
{ 
    int *i;
    int a = &i;
    accept(&ArrMix[MAX]);
    process(a);
    display(a);

    system("pause>0");
}

The code you see above is a program use to create a user-defined array list of numbers. It should accept numbers from the user, display the passed array, positive numbers array and its negative numbers array. it should evaluate items, meaning separating negatives #s from positive numbers then creating an array for each. next is to use a counter to identify how many positive #s and negative #s are in each array. I am having problems in passing the array from one function to another using pointers and calling it in the main function. so please help me?

回答1:

The expression &ArrMix[MAX] returns a pointer to the integer at index MAX in the array. This index is one beyond the array, meaning you pass a pointer to beyond the array to the function which will then happily write to that memory.

Passing an array is as simple as passing any other argument:

accept(ArrMix);

You also have a problem here:

int *i;
int a = &i;

You declare i to be a pointer to an int. Then you use &i which returns the address of the variable i, in other words a pointer to a pointer to an int, and try to assign this double-pointer to a normal int variable.

It seems to me that you might want to return the number of entries is in the array from the access function, and then loop over the entries the user entered in the array and call process for each value. And then in display instead of taking the ArrMix index it should take the size and loop over that to display the ArrMix array.