cpointersvisual-c++stackvisual-c++-2017

Setting a Pointer to a block of stack memory?


I want to create a pointer to a block of stack memory. I don't want to copy the contents, just have a pointer to it. How should I do that?

This is what I tried...

char p[3][2] = { 1,2,3,4,5,6 };
printf("\nLIST:%d,%d,%d,%d,%d,%d\n", p[0][0], p[1][0], p[2][0], p[0][1], p[1][1], p[2][1]); //works fine 

char pc[3][2] = { 1,2,3,4,5,6 };
char **p = (char**)pc;//No error here... but shows on next line when accessing through the pointer
printf("\nLIST:%d,%d,%d,%d,%d,%d\n", p[0][0], p[1][0], p[2][0], p[0][1], p[1][1], p[2][1]);  //ERROR:  an Exception thrown here... 

Solution

  • Pointers are not arrays, and a char** does not retain the information necessary to index a second dimension of any array it might point to.

    So rather than char** you need a pointer to a char[2] array, because otherwise the size of the second dimension of pc is not known to p, such that p[n] cannot be determined.

    You can solve that by declaring a pointer-to-an-array as follows:

    char pc[3][2] = { 1,2,3,4,5,6 }; 
    char (*p)[2] = pc;
    printf("\nLIST:%d,%d,%d,%d,%d,%d\n", p[0][0], 
                                         p[1][0], 
                                         p[2][0], 
                                         p[0][1], 
                                         p[1][1], 
                                         p[2][1] ) ;
    

    For it to produce correct results, the dimension of the p pointer must exactly match the second dimension of the two dimensional array pc array.