How to get the real and total length of char * (char array)?

前端 未结 15 2446
小蘑菇
小蘑菇 2020-11-29 00:37

For a char [], I can easily get its length by:

char a[] = \"aaaaa\";
int length = sizeof(a)/sizeof(char); // length=6

However,

15条回答
  •  一整个雨季
    2020-11-29 01:32

    when new allocates an array, depending on the compiler (i use gnu c++), the word in front of the array contains information about the number of bytes allocated.

    The test code:

    #include 
    #include 
    
    int
    main ()
    {
        int arraySz;
        char *a;
        unsigned int *q;
    
        for (arraySz = 5; arraySz <= 64; arraySz++) {
    
            printf ("%02d - ", arraySz);
    
            a = new char[arraySz];
            unsigned char *p = (unsigned char *) a;
    
            q = (unsigned int *) (a - 4);
            printf ("%02d\n", (*q));
    
            delete[] (a);
    
        }
    }
    

    on my machine dumps out:

    05 - 19
    06 - 19
    07 - 19
    08 - 19
    09 - 19
    10 - 19
    11 - 19
    12 - 19
    13 - 27
    14 - 27
    15 - 27
    16 - 27
    17 - 27
    18 - 27
    19 - 27
    20 - 27
    21 - 35
    22 - 35
    23 - 35
    24 - 35
    25 - 35
    26 - 35
    27 - 35
    28 - 35
    29 - 43
    30 - 43
    31 - 43
    32 - 43
    33 - 43
    34 - 43
    35 - 43
    36 - 43
    37 - 51
    38 - 51
    39 - 51
    40 - 51
    41 - 51
    42 - 51
    43 - 51
    44 - 51
    45 - 59
    46 - 59
    47 - 59
    48 - 59
    49 - 59
    50 - 59
    51 - 59
    52 - 59
    53 - 67
    54 - 67
    55 - 67
    56 - 67
    57 - 67
    58 - 67
    59 - 67
    60 - 67
    61 - 75
    62 - 75
    63 - 75
    64 - 75
    

    I would not recommend this solution (vector is better), but if you are really desperate, you could find a relationship and be able to conclude the number of bytes allocated from the heap.

提交回复
热议问题