Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How string arrays stored in memory?

I know when I make an integer array like below, each item has a particular size and each of them occupies a particular space of memory (e.g. 32 bits).

int[] i = {1, 2, 3, 4, 5};

memory
[addr] [val] [size]
[1000] [1] [32 bit]
[1001] [2] [32 bit]
[1002] [3] [32 bit]
[1003] [4] [32 bit]
[1004] [5] [32 bit]

But when we have a string array like bellow which has different strings with different sizes, how compiler store them into the memory?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

string[] words = {
    "Hi",
    "Foo",
    "Alphabet",
};
Console.WriteLine (words[2]);

// output is "Alphabet"

First, I thought each item occupies memory as big as the largest item, so I changed the second string to something larger than the largest item to see what will happen.

string[] words = {
    "Hi",
    "Hopelessness",
    "Alphabet",
};
Console.WriteLine (words[2]);

// output is still "Alphabet"

But as you can see the third string is still safe from collision.
– why this happened?
– Does compiler store items to different spaces? If so, doesn’t it lower the speed of access to items in a large array?

>Solution :

string[] words = {
    "Hi",
    "Hopelessness",
    "Alphabet",
};

laid out like this

words=>|Ref1|Ref2|Ref3|
         |    |     |
         |    |      > "Hi"
         |     > "Hopelessness"
          > "Alphabet"

‘words’ is an array of references to strings. a reference is basically a smart pointer. The actual strings are in the heap and the references point to them

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading