Reputation: 21
I've got following code:
#include <iostream>
#include "note.h";
using namespace std;
void prompt() {
string opt;
system("CLS");
cout << "What do you want to do?" << endl << "1. Browse" << endl << "2. Add" << endl;
cin >> opt;
if(opt=="1") {
cout << "Not yet.";
} else if(opt=="2") {
system("CLS");
string title;
string content;
cout << "Title:" << endl;
cin >> title;
cout << "Content:" << endl;
cin >> content;
Note note(title, content);
} else {
prompt();
}
}
int main() {
int size = 0;
Note* tNote = new Note[size];
delete [] tNote;
prompt();
system("PAUSE");
return 0;
}
My question is - how can I add another Note to tNote inside prompt() function and increase their size defined in main()?
Currently when I want to do size++; inside prompt() I'm getting "undefined identifier".
Upvotes: 0
Views: 435
Reputation: 3420
Since you cannot use vector, you're just going to have to keep the size of the array in a global variable outside the main function. Just move the "int size = 0" line to above the main function, and you'll be able to access it from elsewhere.
Please note: this is terrible as a design practice, but it will solve your immediate problem and let you move on with your learning. If you're teacher's any good they will explain that there are better ways to accomplish this (i.e. using STL, or implementing your own dynamic array class and passing that by reference).
Upvotes: 0
Reputation: 206508
Simplest & elegant way is to use a std::vector
and pass it as an argument by reference to function prompt()
.
Once you use vector, you don't have to bother about the memory allocations dilemnas like one you are facing now, vector automatically grows in size to accomodate your objects.
Since, it is homework I am not going to give you a code example.
Read about std::vector and passing arguments by reference in C++ and you should be able to solve your homework.
Upvotes: 2