2014-01-09 20 views
-1
#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"); 
} 

您在上面看到的代碼是程序用於創建用戶定義的數組數組列表。它應該接受來自用戶的數字,顯示傳遞的數組,正數數組和負數數組。它應該評估項目,這意味着從正數中分離負數#s然後爲每個數組創建一個數組。接下來是使用計數器來確定每個數組中有多少個正數#和負數#。 我有問題將數組從一個函數傳遞到另一個使用指針並在主函數中調用它。所以請幫助我?如何在主函數中傳遞數組。 w/C++

回答

1

表達式&ArrMix[MAX]返回指向數組中索引爲MAX的整數的指針。這個索引超出了數組的範圍,這意味着你將一個指向數組的指針傳遞給函數,然後這個函數將會愉快地寫入該內存。

傳遞一個數組作爲傳遞任何其他參數一樣簡單:

accept(ArrMix); 

你這裏也有一個問題:

int *i; 
int a = &i; 

您聲明i是一個指向int。然後,您使用&i,它返回變量i的地址,換句話說,指向指向int的指針,並嘗試將此雙指針分配給正常的int變量。

在我看來,您可能想要返回來自access函數的數組中的條目數,然後遍歷用戶在數組中輸入的條目並針對每個值調用process。然後在display而不是採取ArrMix索引它應該採取的大小和循環,以顯示ArrMix陣列。

+0

這是我的代碼中唯一錯誤的東西嗎? – JRYS

+0

@JRYS當然可能還有其他問題,但那些是我能夠立即看到的兩個最大的問題。您應該學習如何使用調試器,因爲那樣您可以逐行瀏覽代碼,並查看真正發生的情況。 –

+0

修復了我的代碼!我知道了。謝謝! – JRYS