How to calculate size of array from pointer variable?

前端 未结 3 1011
南旧
南旧 2020-12-06 15:22

i have pointer of array(array which is in memory). Can i calculate the size of array from its pointer ? i dont know actually where is the array in memory. i only getting poi

3条回答
  •  太阳男子
    2020-12-06 16:18

    You cannot do this in C. The size of a pointer is the size of a pointer, not the size of any array it may be pointing at.

    If you end up with a pointer pointing to an array (either explicitly with something like char *pch = "hello"; or implicitly with array decay such as passing an array to a function), you'll need to hold the size information separately, with something like:

    int twisty[] = [3,1,3,1,5,9];
    doSomethingWith (twisty, sizeof(twisty)/sizeof(*twisty));
    :
    void doSomethingWith (int *passages, size_t sz) { ... }
    

    The following code illustrates this:

    #include 
    
    static void fn (char plugh[], size_t sz) {
        printf ("sizeof(plugh) = %d, sz = %d\n", sizeof(plugh), sz);
    }
    
    int main (void) {
        char xyzzy[] = "Pax is a serious bloke!";
        printf ("sizeof(xyzzy) = %d\n", sizeof(xyzzy));
        fn (xyzzy, sizeof(xyzzy)/sizeof(*xyzzy));
        return 0;
    }
    

    The output on my system is:

    sizeof(xyzzy) = 24
    sizeof(plugh) = 4, sz = 24
    

    because the 24-byte array is decayed to a 4-byte pointer in the function call.

提交回复
热议问题