How to dereference an array element (C++) -
i wanted create array of specific size using variable, allegedly way utilize pointers.
int size = 5; string* myarray = new string[size];
i want assign element array variable, believe work through dereferencing. next line of code doesn't work. how prepare it?
string line; myarray[0] = "hello"; line = *myarray[0];
edit:
i want clarify something: using normal "myarray[0]" code doesn't work either. compiles, causes crash. here's more specific code regarding want do.
void myclass::setline(string line) { myline = line; /*this private variable in myclass*/ } /////////////// myclass* elements = new myclass[size]; elements[0].setline(myarray[0]);
i want assign array element private variable class, programme crashes when seek assign value private variable.
if know size @ compile time, can utilize normal array. if know size @ runtime, still utilize std::vector
, far easier utilize manual allocation.
anyway, if want larn pointers array managing, maintain in mind index operator equivalent add-on , dereference, i.e. ar[i]
same *(ar + i)
. in other words, indexing dereferencing @ offset.
as such, no dereference needed. drop asterisk in failing line.
c++ arrays pointers element dereference
No comments:
Post a Comment