0

If I pass a vector by reference and and I push new elements to the vector and it has to dynamically resize the array while I push elements in the function, will the vector now be at a different location? How does the program ensure that it points to the new dynamically allocated location? Is it using a pointer to the pointer that points to the current array memory location which can be modified after resizing to point to a new contiguous memory location under the hood?

void func(vector<int> &vect) 
{ 
   vect.push_back(30); 
} 

int main() 
{ 
    vector<int> vect; 
     func(vect);

}
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
vkaul11
  • 4,098
  • 12
  • 47
  • 79

1 Answers1

0

The answer is yes. You can confirm this to yourself by trying to figure out what's happening in your code sample. The key insight is that anything allocated non-dynamically must have a fixed size at allocation time.

You don't have a pointer here, so the core data structure of the vector is getting allocated on the stack, where it can't just grow into other things that are potentially on top of it in the stack. For instance, while you're inside func(), the function call to func is on the stack on top your vector variable. It's impossible for it grow there without overwriting the stack frame for your function call. If it did that, your program would crash when trying to return from func.

So, the only way it could possibly grow is if, internally, it dynamically allocated memory in a different location as needed. So, this must be what's happening under the hood.

Jan Krüger
  • 17,870
  • 3
  • 59
  • 51
  • Yes so the pointer to the vector and pointer to the first element of the vector are different right? – vkaul11 Apr 11 '19 at 23:00
  • Kind of. There isn't really a pointer to only the first element of the vector, in the sense you'd have it in a linked list. Instead, the vector's data structure contains a pointer to the storage area where *all* of the elements are stored. That this internal pointer also points to the first element is basically an implementation detail - for all you know it could be doing something different and less sane instead. :) – Jan Krüger Apr 11 '19 at 23:02
  • I am talking more in terms of Arraylist like you have in java or a simple array where the first element pointer is sufficient to access the rest of the elements as long as you know the array size. – vkaul11 Apr 11 '19 at 23:10
  • Sure, and that's *probably* what vector does internally, but you can't know for sure... and you don't get to access `vector`'s internals without trickery, anyway. :) – Jan Krüger Apr 11 '19 at 23:12