In C++ how does "sizeof(array)/sizeof(array[0])" give the number of elements in an array? Why isn't it affected by the length of each element? I'm playing around with C++ and was looking at how to loop through an array of unknown length. The following code was suggested and works perfectly from the little testing I've done:
std::string words[5] = {&quot;Lorem ipsum dolor sit amet orci aliquam.&quot;, &quot;Hi&quot;, &quot;Welcome&quot;, &quot;World&quot;, &quot;LoopyDoopyDoo&quot;};
for (int i = 0; i &lt; sizeof(words)/sizeof(words[0]); i++){
     DO STUFF
}

From what I've read the sizeof() operator returns the size of a variable in bytes.
What I don't understand is how this isn't affected by the number of characters in each element of the array. I printed out the sizeof() value to check and the array size is always evaluated at 160 bytes and element 0 as 32 no matter how many characters are present. I thought that it might be allocating 32 bytes but not using them all so I stored some text that should use 40 bytes, but still no change. Am I missing something here? Is text stored differently in C++?
Any help in understanding how this actually works would be appreciated, thanks!
C and C++ are low-level languages that give the programmer precise control over the memory layout. Each object takes a constant amount of memory which is fully determined (on a given implementation) by its type. The sizeof operator lets programs know this size.
An object may contain pointers. The data that the pointers points to, if any, is not part of the object. The size of an object is what some higher-level language might call the “shallow” size: it only considers the object itself, not other objects that the object references.
For example, an object of type std::string has a certain size. This size is independent of the content of the string. This means that the only way to implement std::string for strings of unbounded length is for the std::string object to contain a pointer to the actual content of the string. sizeof(std::string) is the size of this pointer plus other data that the std::string type keeps track of (that would typically be the length of the string, the size allocated for the string, a pointer to the class's method table). It has no relation with the length of the string.
An array is an object which consists of several objects of the same type. Since the elements of the array all have the same type, they all have the same size.