Declaring arrays

I’m having some issues declaring arrays in vcs. For instance:
int NamesArray[] = [“name1”,“name2”,“name3”,“name4”,“name5”,“name6”];
will give me an error:
expected variable name or ‘this’ in lambda capture list int blueNamesArray[] = [“name1”,“name2”,“name3”,“name4”,“name5”,“name6”];

I’m probably missing something very simple. Any help?

I’m guessing you are coming from js or something?
The C++ syntax to initializing an array is

int array[] = {1, 2, 3, 4, 5};

However, you can’t assign a string to an integer, array or not.
Instead, you can use const char* (the C way) or std::string (the C++ way) to store the string.

3 Likes

You are trying to store Strings in an int array, primitive data to object will not work out. Plus, use curly braces, so:
String[] names = {“name”, “name”, “name”};
etc. Or to fill it later, do this:
String[] names = new String[length]
But remember, array length is immutable

Thanks for the help, and yes I’ve been using js.

I’m pretty sure you are mixing up another language.
A String object does not exist in C, and the new command does not work in the way you think (it does dynamic initialization which returns a pointer).
This is the use of new

int* array = new int[length];
array[0] = 1;

Read here and here.

The way a string is represented is an array of char, so const char* is how they do it in C.

std::string is a wrapper for this, which is object oriented and much nicer.
Fortunately,

std::string array[] = {"hello", "goodbye"};

is valid syntax.

@Palpatine I would look into reading some C/C++ guides. These languages are quite a bit less intuitive than js, and require some lower level management. You just can’t be as flexible as js.
The only time you are able to use the = {1, 2} syntax is on initialization.
You can’t do

int array[];
array = {1, 2, 3};

The size of the array can only be controlled when the array is created.

The solution people use is to make use of std::vector, which is a resiable array. here and here.
Then, you can do

std::vector<std::string> array = {"hello", "goodbye"};
array.push_back("greetings");
array = {"hi"};

This is a much better solution than to use new.

1 Like

Yeah my bad. I was teaching about java earlier, slipped my mind.