Quick strlen question

2019-01-19 20:45发布

I've come to bother you all with another probably really simple C question.

Using the following code:

int get_len(char *string){

    printf("len: %lu\n", strlen(string));

    return 0;
}

int main(){

    char *x = "test";
    char y[4] = {'t','e','s','t'};

    get_len(x); // len: 4
    get_len(y); // len: 6

    return 0;
}

2 questions. Why are they different and why is y 6? Thanks guys.

EDIT: Sorry, I know what would fix it, I kind of just wanted to understand what was going on. So does strlen just keep forwarding the point till it happens to find a \0? Also when I did strlen in the main function instead of in the get_len function both were 4. Was that just a coincidence?

标签: c string strlen
8条回答
Rolldiameter
2楼-- · 2019-01-19 21:20
char y[5] = {'t','e','s','t','\0'};

would be the same as

char *x = "test"; 
查看更多
混吃等死
3楼-- · 2019-01-19 21:20

As others have said, you just need to make sure to end a string with the 0 or '\0' character. As a side note, you may check this out: http://bstring.sourceforge.net/ . It has O(1) string length function, unlike the C/C++ strlen which is error prone and slow at O(N), where N is the number of non-null characters. I don't remember the last time when I used strlen and it's friends. Go for safe & fast functions/classes!

查看更多
登录 后发表回答