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

前端 未结 15 2525
小蘑菇
小蘑菇 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条回答
  •  旧时难觅i
    2020-11-29 01:20

    You can implement your own new and delete functions, as well as an additional get-size function:

    #define CEIL_DIV(x,y) (((x)-1)/(y)+1)
    
    void* my_new(int size)
    {
        if (size > 0)
        {
            int* ptr = new int[1+CEIL_DIV(size,sizeof(int))];
            if (ptr)
            {
                ptr[0] = size;
                return ptr+1;
            }
        }
        return 0;
    }
    
    void my_delete(void* mem)
    {
        int* ptr = (int*)mem-1;
        delete ptr;
    }
    
    int my_size(void* mem)
    {
        int* ptr = (int*)mem-1;
        return ptr[0];
    }
    

    Alternatively, you can override the new and delete operators in a similar manner.

提交回复
热议问题