C:自定义strlen()库函数 [英] C: Custom strlen() library function

查看:114
本文介绍了C:自定义strlen()库函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了 strlen()函数的版本。

unsigned int my_strlen(char *p)
{
    unsigned int i = 0;

    while(*p!='\0')
    {
        i++;
        p++;
    }

    return i;
}

每次运行都会给我正确的输出。但是我的同事说的是这段代码在字符长度大于 1个字节的系统上可能会引起问题。是这样吗?

It gives me correct output everytime i run.But my collegues are saying this code may cause problem on systems where length of character is greater than 1 byte. Is that so ??

因此他们修改了代码,如下所示:

So they modified the code as following:

unsigned int my_strlen(char *p)
{
    unsigned int i = 0;
    char *start = p;

    while(*p!='\0')
    {
        i++;
        p++;
    }

    return p - start;
}

我一直认为在C中一个字符长1个字节。

I always thought in C a character is 1 byte long.

前一个代码段比后者好,反之亦然?

Is former snippet is better than the latter or vice versa ??

推荐答案

在C中保证 sizeof(char)为1,所以您是对的。

It is guaranteed in C that sizeof(char) is 1, so you are right.

到添加一些真实性,直接引用 C11 ,第§6.5.3.4章, sizeof _Alignof 运算符

To add some authenticity, directly quoting C11, chapter §6.5.3.4, The sizeof and _Alignof operators


sizeof 应用于类型为 char unsigned char
<$ c $的操作数c> signed char (或其限定版本),结果为1。[....]

When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. [....]

也就是说,指针算术支持数据类型,因此无论如何,第二种方法对于预期的作用没有任何意义。两种情况下,您都在 p 上操作,这是 char * ,因此效果将相同。

That said, pointer arithmetic honors the data type, so the second approach does not make any sense in the respect of what is is expected to do, anyway. Both the case, you're operating on p, which is char*, so the effect will be the same.

这篇关于C:自定义strlen()库函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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