Reputation: 87
I'm new to C++, and I want to know if this valid.
So I want to create an array of strings, but I wont know the size of the array I need until a value is passed in to a function within the class I'm working in. So, can I do this:
string sList[];
void init(unsigned int size=1)
{
sList = new string[size];
}
I'm sorry if this is a dumb question, but I'm a Java guy new to C++.
EDIT: This is an assignment that involves me writing an array wrapper class. If I could use vector<>, trust me, I would.
Upvotes: 0
Views: 266
Reputation: 477070
The right way to do this in C++:
#include <string>
#include <vector>
std::vector<std::string> sList;
void init(unsigned int size = 1)
{
sList.resize(size);
}
int main()
{
init(25);
}
Upvotes: 1
Reputation: 110658
A new-expression (such as new string[size]
) returns a pointer to a dynamically allocated object. In this case, it returns a pointer to the first string
object in the dynamically allocated array. So to make this work, sList
should be a pointer:
string* sList;
It is important to remember that you must always delete
/delete[]
and object that has been created with new
/new[]
. So you must at some point delete[] sList
. If you don't do this, the memory allocated for the array of string
s will “never” be deallocated.
However, you'll be in a much better situation if you use a std::vector<std::string>
instead, rather than doing your own dynamic allocation.
Upvotes: 1
Reputation: 2420
This is correct, although string sList[]
should be string *sList
. Don't forget the delete [] sList
at the end.
As many others say, you can use std::vector
if you want, but getting some practice with arrays is an excellent way to learn how the memory management works and I encourage you to explore it further.
Upvotes: 1