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

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

    This may sound Evil™ and I haven't tested it, but how about initializing all values in an array at allocation to '\0' and then using strlen() ? This would give you your so-called real value since it would stop counting at the first '\0' it encounters.

    Well, now that I think about it though, please don't Ever™ do this. Unless, you want to land in a pile of dirty memory.

    Also, for the allocated memory or the total memory you may use the following functions if your environment provides them:

    • msize()
    • malloc_usable_size()

提交回复
热议问题