0

私はC ++が初めてで、std::vectorの助けを借りずに次の2つのことをやろうとしていました(これは以前に行われました)

  1. 整数の配列を定義しますが、配列のサイズはわかりません。
  2. この配列を別の関数に渡し、配列に格納されているすべての値を出力します。

    int _tmain()
    {
    
        int* a = NULL;   
        int n;          
        std::cin >> n;        
        a = new int[n];  
        for (int i=0; i<n; i++) {
            a[i] = 0;   
        }
    
        testFunction(a,n);
        delete [] a;  
        a = NULL;    
    
    }
    void testFunction( int x[], int n)
    {
        for(int i =0;i<n;++n)
        {
            std::cout<<x[i];
        }
    }
    

しかし、10バイトのメモリを割り当てておらず、常に1つのメモリが0でいっぱいになっていることがわかります。何か不足している場合は誰か助けてもらえますか? または、ベクトル以外にこれに代わる方法はありますか。前もって感謝します

iの代わりに++nを入れていることに気付いたので、1つのことを修正しました

int _tmain()
{

    int* a = NULL;   
int n;          
std::cin >> n;        
a = new int[n];  
for (int i=0; i<n; i++) {
    a[i] = i;   
}

testFunction(a,n);
delete [] a;  
a = NULL;    

}
void testFunction( int x[], int n)
{
    for(int i =0;i<n;++i)
    {
        std::cout<<x[i];
    }
}
4

1 に答える 1

3

あなたの問題をすべて理解しているかどうかはわかりませんが、入力ミス for(int i =0;i<n;++n) によりtestFunction非常に長いループが発生しました。

書く:

for(int i =0;i<n;++i) 

これはあなたの n "0" を印刷します

于 2013-01-16T09:30:16.033 に答える