快速strlen的问题

编程入门 行业动态 更新时间:2024-10-27 18:32:28
本文介绍了快速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的问题

本文发布于:2023-07-30 00:47:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1245056.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   strlen

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!