所以我有這樣的代碼,但它不輸出,加上第4個值後,正確的東西,就好像這一切被刪除,並不會添加,直到下一次運行增加值動態數組
#include <iostream>
using namespace std;
const int DEFAULT_CAPACITY = 2;
void addValue(int data[], int& logSize, int& physSize, int newValue)
{
// DATA DICTIONARY
int *temp;
if (logSize == physSize)
{
physSize *= 2;
temp = new int[physSize];
for (int i = 0; i <= logSize; i++)
{
temp[i] = data[i];
cout<<temp[i]<<endl;
}
delete [] data;
data = temp;
}
data[logSize] = newValue;
for (int i = 0; i <= logSize; i++)
{
cout<<data[i]<<endl;
}
logSize++;
}
void printData(int data[], int logSize)
{
cout<<endl;
cout<<"ARRAY DATA:"<<endl;
for (int i = 0; i < logSize; i++)
{
cout<<data[i]<<endl;
}
}
void main()
{
//DATA DICTIONARY
int *data;
int logSize;
int physSize;
int newValue;
char choice;
physSize = DEFAULT_CAPACITY;
logSize = 0;
data = new int[physSize];
do
{
cout<<"What would you like to do?"<<endl;
cout<<"(A)dd value to array"<<endl;
cout<<"(D)isplay all values"<<endl;
cout<<"(Q)uit"<<endl;
cin>>choice;
if (choice == 'A' || choice == 'a')
{
cout<<"What integer do you want to add? ";
cin>>newValue;
addValue(data, logSize, physSize, newValue);
}
if (choice == 'D' || choice == 'd')
{
printData(data, logSize);
}
cout<<endl;
} while (choice != 'Q' && choice != 'q');
}
使用[std :: vector](http://www.cplusplus.com/reference/vector/vector/)。除非明確使用引用(並且不能引用數組),否則C++參數傳遞通常是[傳值](http://en.wikipedia.org/wiki/Pass-by-value) –
@BasileStarynkevitch - this是一個任務,不能使用向量。 – cb1295
這裏的問題究竟是什麼?你能更具體地瞭解發生了什麼?提供基本的輸出等... – Durandal