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

前端 未结 15 2432
小蘑菇
小蘑菇 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

    • In C++:

    Just use std::vector which keep the (dynamic) size for you. (Bonus, memory management for free).

    Or std::array which keep the (static) size.

    • In pure C:

    Create a structure to keep the info, something like:

    typedef struct {
        char* ptr;
        int size;
    } my_array;
    
    my_array malloc_array(int size)
    {
        my_array res;
        res.ptr = (char*) malloc(size);
        res.size = size;
        return res;
    }
    
    void free_array(my_array array)
    {
        free(array.ptr);
    }
    

提交回复
热议问题