How to calculate size of array from pointer variable?

前端 未结 3 1012
南旧
南旧 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:12

    No. arrays in C doesn't have this info. you should hold a variable "next" to the array with this data.

    if you have the array it self you can use the sizeof to get his size in compilation stage.

    char array1[XXX];
    char* pointer1 = array1;
    sizeof(array1); // this is XXX
    sizeof(pointer1); // this is the size of a pointer in your system
    

    you should do the following and use the variable in you program (or pass it to function when you passing the array to a function)

    int array1size = sizeof(array1);
    
    0 讨论(0)
  • 2020-12-06 16:18

    No, you cannot calculate the size of the array. Objects in C do not carry type information, so you must arrange to know the size of the array ahead of time. Something like this:

    void my_function(int array[], int size);
    
    0 讨论(0)
  • 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 <stdio.h>
    
    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.

    0 讨论(0)
提交回复
热议问题