strlen
takes a pointer value, a memory address, and from this memory location counts the bytes until it hits one of value 0 (in this context often called "null terminator"). Since array2
does not contain a byte of zero, what strlen
reports depends on how the compiler placed all the variables on stack.
For whatever reason, the stack grows backwards. That means array2
is likely placed before array1
, and k
right before that one. strlen
would count the characters in array2
, then the ones in array1
, and then find a byte of zero that happened to be there. You could check by printing the first 8 bytes of array2
(which contains only 3).
Even the same compiler with different settings might also align the individual arrays at addresses divisible by 8. In that case, your results might be completely different, likely 3, but it depends on whatever those extra bytes contain (likely 0 for a freshly started programme).
For the size of structures, one would use the sizeof
operator, like with a variable int k = sizeof(array2);
or with a type int l = sizeof(long);
. It returns the number of bytes taken by the variable's type. If your variable is a char[3]
, it would return 3. If it were an int[6]
, it would likely report 24. If you want to get the number of elements, that would be sizeof(array2)/sizeof(array2[0])
, total size divided by the size of a single element.
Note that this only works for arrays you access by their original names, if you pass them to a function, they are passed as the memory address of their first element, losing the size information.