快速strlen的问题 [英] Quick strlen question

查看:107
本文介绍了快速strlen的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来打扰你所有的另一个可能真正简单的C的问题。

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

使用以下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的问题。为什么他们不同的,这是为什么Y 6?谢谢你们。

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

编辑:对不起,我知道会解决它,我有种只是想知道发生了什么事情。因此,没有strlen的只是不停的转发,直到点碰巧找到\\ 0?此外,当我在主函数,而不是在get_len并strlen函数两者都是四是,只是一个巧合?

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?

推荐答案

是不是空终止。 的strlen()直到碰到一个空字符计数的字符。你的月份找到一个6之后,但它可以是任何数量。试试这个:

y is not null-terminated. strlen() counts characters until it hits a null character. Yours happened to find one after 6, but it could be any number. Try this:

烧焦Y [] = {'T','E','S','T','\\ 0'};

下面就是的实现的strlen()可能看起来像(从我的头顶 - 没有我的K&安培; R书方便,但我相信,有鉴于有实现):

Here's what an implementation of strlen() might look like (off the top of my head -- don't have my K&R book handy, but I believe there's an implementation given there):

size_t strlen(const char* s)
{
    size_t result = 0;
    while (*s++) ++result;
    return result;
}

这篇关于快速strlen的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆