开发者

How to properly dereference multidimensional arrays without []-operator

开发者 https://www.devze.com 2023-04-08 22:34 出处:网络
So, I\'ve figured out how to dereference a multidimensional array like this: #include <tchar.h> #include <iostream>

So, I've figured out how to dereference a multidimensional array like this:

#include <tchar.h>
#include <iostream>

wchar_t g_pppwcSymbol[2][3][4];

int main(int argc, TCHAR **argv) 
 {
     (* (*( (*(g_pppwcSymbol+1) )+2 )+3 ) ) = L'K';
     std::wcout<<g_pppwcSymbol[1][2][3];
     std::wcin.get();
     return 0;
 }

Output: K

However, I've also heard that the compiler transforms this into a 1-dimensional array, is that correct? This would mean that all the wchar_t elements follow up each other in the memory. So there must be a way to do something like this:

***(g_pppwcSymbol + x) = value;

However I'm not sure how this works exactly. Could someone elaborate?


EDIT:

this seems to work so far:

int main(int argc, TCHAR **argv) 
 {
     /*(* (*( (*(g_pppwcSymbol+1) )+2 ) + 3)) = L'K';*/
     /*std::wcout<<g_pppwcSymbol[1][2][3];*/
     ***(g_pppwcSymbol + 1) = L'K';
     std::wcout<<g_pppwcSymbol[1][0][0];
     std::wcin.get();
     return 0;
 }

output: K


NEXT EDIT:

Working model:

static const int X = 2;
static const int Y = 3;
static const int Z = 4;
wchar_t g_pppwcSymbol[X][Y][Z];

int main(int argc, TCHAR **argv) 
 {
     int iAccess = ((Y*Z) * 1) + ((开发者_运维问答Z) * 2) + 3;
     *( (**g_pppwcSymbol) +  iAccess) = L'K';
     std::wcout<<g_pppwcSymbol[1][2][3];
     std::wcin.get();
     return 0;
 }

Output: K


The compiler actually transforms the [] operator into just those mathematical calculations, so you are going about this the hard way... But it's an interesting exercise so I'll play along.


g_pppwcSymbol[2][3][4] is actually a 2 elements large array of 3 elements large array of 4 elements large. Thus,

g_pppwcSymbol + ((3 * 4) /* size of first level array element */ * 1) + (4 /* size of second level array element */ * 2) + 1 /* size of third level array element */ * 3;

should give you the position of the last item of the last array of the last array. As long as each element is 1 byte large.

The array simply is a memory area the size of "element_count * element_size and the [] operator takes the array location as a pointer and adds element_size * index. It may contain other arrays since it can compute their sizes the same way as other memory structures.

BTW, I'm sure you'll find plenty of documentation about this in details all over the internet.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号