Search code examples
c++arrayspointerselementdereference

How to dereference an array element (C++)


I wanted to create an array of a specific size using a variable, but allegedly the only way to do that is to use pointers.

int size = 5;
string* myArray = new string[size];

I now want to assign an element from this array to another variable, which I believe will only work through dereferencing. The following line of code doesn't work. How do I fix it?

string line;

myArray[0] = "Hello";
line = *myArray[0];

Edit:

I just want to clarify something: Using the normal "myArray[0]" code doesn't work either. It compiles, but causes a crash. Here's some more specific code regarding what I want to do.

void MyClass::setLine(string line)
{
    myLine = line; /*This is a private variable in MyClass*/
}

///////////////

MyClass* elements = new MyClass[size];

elements[0].setLine(myArray[0]);

I want to assign the array element to a private variable from a class, but the program crashes when I try to assign the value to the private variable.


Solution

  • If you know the size at compile time, you can use a normal array. If you only know the size at runtime, you could still use a std::vector, which is far easier to use than manual allocation.

    Anyway, if you really want to learn about pointers for array managing, keep in mind that the index operator is equivalent to addition and dereference, i.e. ar[i] is the same as *(ar + i). In other words, indexing is just dereferencing at an offset.

    As such, no extra dereference is needed. Just drop the asterisk in the failing line.