(e-mail address removed):
Hi friends,
I have question, who knows is very welcome:
Assume we have a fragment of code:
typedef char String [46];
String* pStr = new String[10];
Your questions have been answered already. However, there is a
question f or
you: why this piece of code was not written simply as:
std::vector<std::string> pStr(10);
Or was it just a language tour question?
Cheers
Paavo
Thank you for your reply.
Yes, they're just my questions to specify how is the memory allocated
for the pointer.
First, we type define String as char[46], right?
Then, we new String[10]; but i wonder how is the memory allocated? is
it like a two-dimension array of char in which there are number of
rows is 46 and columns is 10?
Basically yes, except that the meaning of rows and columns depends on how
you interpret your data. The computer memory is addressed one-
dimensionally so there is no inherent meaning for these terms.
The memory is allocated in one piece. The size of the memory block is 10
*sizeof(String), plus any potential overhead related to the array new[]
constructor, if the compiler decides to use any. The first String lies at
the returned pointer address pStr, the next is sizeof(String) bytes
further (accessed as pStr[1]) etc. For example, one can access the last
byte in the first String as pStr[0][45];
The sizeof(String) itself is 46 as sizeof(char) is 1 by definition. I
believe compiler is not allowed to insert any padding. This number is not
divisible even by 4, meaning that the individual strings are not aligned
on bus width or cache line boundaries and accessing them may thus have
some performance penalty. Otherwise this is probably the most efficient
format for an array of strings, assuming that most of them are always 45
characters long or close to it.
The memory is not initialized as the String type is a POD. One can cure
this by using this syntax to zero-initialize the content:
String* pStr = new String[10]();
One must take care when filling in the array as it would be easy to
overrun the string borders. One cannot store larger strings than 45
characters, one cannot change the number of strings in the array
afterwards, one has to keep track the number of strings in the array
separately, and one has to take care to delete[] the array after use. All
these drawbacks mean that using this kind of array is not really
indicated in most situations (save maybe for interfacing some old Fortran
code?). If the size of String were 48 or 64, then it might be maybe
useful in some kind of specific performance-critical processing.
hth
Paavo