I am watching lectures on C++ from the stanford online courses website. I have a slight problem in understanding how memory is allocated for a string in C++. Basically when you declare a vector the constructor is called and memory is allocated for the array arr, numUsed and numAllocated are initialized.
The first question I have is how much memory is allocated initially? Is it 2 bytes or is it 3 bytes with memory for the null character?
Secondly, in the member function add, the statement arr[numUsed++] = s assigns the first string to arr[0] and the next string to arr[1]. Now how are the strings stored in memory? How can I access individual characters of arr[0] or arr[1](is it arr[0][0], arr[0][1]?)?
Thanks. I hope I am clear with my questions. I have pasted the code from the lecture below.
* File: myvector.h
* ----------------
*
* Created by Julie Zelenski on 2/22/08.
*
*/
#ifndef _myvector_h
#define _myvector_h
#include "genlib.h"
class MyVector
{
public:
MyVector();
~MyVector();
int size();
void add(string s);
string getAt(int index);
private:
string *arr;
int numUsed, numAllocated;
void doubleCapacity();
};
#endif
/*
* File: myvector.cpp
* ------------------
*
* Created by Julie Zelenski on 2/22/08.
*
*/
#include "myvector.h"
MyVector::MyVector()
{
arr = new string[2];
numAllocated = 2;
numUsed = 0;
}
MyVector::~MyVector()
{
delete[] arr;
}
int MyVector::size()
{
return numUsed;
}
string MyVector::getAt(int index)
{
if (index < 0 || index >= size())
Error("Out of bounds");
return arr[index];
}
void MyVector::add(string s)
{
if (numUsed == numAllocated)
doubleCapacity();
arr[numUsed++] = s;
}
void MyVector::doubleCapacity()
{
string *bigger = new string[numAllocated*2];
for (int i = 0; i < numUsed; i++)
bigger[i] = arr[i];
delete[] arr;
arr = bigger;
numAllocated*= 2;
}