As we know, multi-array like int array1[3][2] = {{0, 1}, {2, 3}, {4, 5}}
; is contiguous, so it is exactly the same as int array2[6] = { 0, 1, 2, 3, 4, 5 };
for (int *p = *array1, i = 0; i < 6; i++, p++)
{
std::cout << *p << std::endl;
}
0
1
2
3
4
5
Then, I have these codes:
char *textMessages[] = {
"Small text message",
"Slightly larger text message",
"A really large text message that ",
"is spread over multiple lines*"
};
I find that its layout is not the same as int[3][2]:
- For every sub message, like
"Small text message"
, every alpha is contiguous and offset is1
(sizeof(char) == 1). - However, the final element of
"Small text message"
--e
and the first element of"Slightly larger text message"
--S
is not contiguous in memeary:
char *textMessages[] = {
"Small text message",
"Slightly larger text message",
"A really large text message that ",
"is spread over multiple lines*"
};
char *a = *(textMessages)+17, *b = *(textMessages + 1), *c = *(textMessages + 1) + 27, *d = *(textMessages + 2), *e = *(textMessages + 2) + 31, *f = *(textMessages + 3);
std::ptrdiff_t a_to_b = b - a, c_to_d = d - c, e_to_f = f - e;
printf("they(a b c d e f) are all messages's first or final element: %c %c %c %c %c %c\n", *a, *b, *c, *d, *e, *f);
printf("\n\naddress of element above: \n%p\n%p\n%p\n%p\n%p\n%p\n", a, b, c, d, e, f);
printf("\n\nptrdiff of a to b, c to d and e to f: %d %d %d\n", a_to_b, c_to_d, e_to_f);
they(a b c d e f) are all messages' first or final element: e S e A t i
address of element above:
002F8B41
002F8B44
002F8B5F
002F8B64
002F8B83
002F8B88
ptrdiff of a to b, c to d and e to f: 3 5 5
My question is:
- What does
3 5 5
mean here? - Why
3 5 5
, not5 5 5
- What's the layout here?
Edit: I don't think this question duplicates of How are multi-dimensional arrays formatted in memory?, because what I ask is not the same as that question's doubt and the solution should not that's question's answers.