简体   繁体   中英

Array initialization in c++

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.

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.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM