I should know this and probably did at one stage but just wondering what is the difference between &array and &array[0], so the first one is the address of the start of the array which I thought would be the same as &array[0] ie same index and in this case hence same memory address
but when I use
1 2 3
in.read((char*)(&number),numberSize);
the program seems to crash
and when I use
1 2 3 4
in.read((char*)(&number[0]),numberSize);
the function exits gracefully,also when I print both of them the former prints the address and the latter prints the name?
'number' isn't an array, it's an std::string! The memory layout of an std::string looks roughly like this:
1 2 3 4 5
class string{
char *internal_array;
size_t length;
//...
};
When you do
in.read((char*)(&number),numberSize);
You're writing directly to the memory of the object. Thus internal_array will almost certainly end up pointing to garbage and length will almost certainly end up as nonsense.
When you do
in.read((char*)(&number[0]),numberSize);
First you're calling std::string's operator[]() overload, which in this case will return a reference to the first char of the string. Then you get the address of that char. Since std::string guarantees representing the string as a flat array, &number[0] gets you the pointer to the internal array (as long as size() != 0. If size() == 0 the behavior is undefined).
If 'number' was actually an array you'd be right, (char *)&array and (char *)&array[0] would be equivalent.
EDIT:
&array is the same as &(&(array[0]))
&&x is not a valid expression (unless x overloads operator&()).
in.read((char*)(&number),numberSize);
You're writing directly to the memory of the object. Thus internal_array will almost certainly end up pointing to garbage and length will almost certainly end up as nonsense.
When you do
in.read((char*)(&number[0]),numberSize);
First you're calling std::string's operator[]() overload, which in this case will return a reference to the first char of the string. Then you get the address of that char. Since std::string guarantees representing the string as a flat array, &number[0] gets you the pointer to the internal array (as long as size() != 0. If size() == 0 the behavior is undefined).
Oh ok that does make sense so with the former we are writing the data to the actual string object itself
and with the latter using the strings overloaded [] operator we are actually writing the data to the actual string part or the memory that actually holds the strings character data