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

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

    Legit question. I personally think people confuse pointers with arrays as a result of character pointers (char*), which serve almost the same purpose as character arrays (char __[X]). This means that pointers and arrays are not the same, so pointers of course don't contain a specific size, only an address if I could say so. But nonetheless you can try something similar to strlen.

    int ssize(const char* s)
    {
        for (int i = 0; ; i++)
            if (s[i] == 0)
                return i;
    
        return 0;
    }
    

提交回复
热议问题