使用指针的字符串长度 [英] String length using pointers

查看:91
本文介绍了使用指针的字符串长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些代码技巧.我找到了一个我掌握的基础知识,但我不明白为什么它退出了.它与while循环中的字符串指针有关.通常我不处理字符串,因为我主要在嵌入式系统...小工具上工作.我需要了解为什么当字符串指针没有递增时会结束.

I was looking up some code tricks. I found one that I get the basics but I don't understand why it exits. It has to do with a string pointer in a while loop. Usually I don't deal with strings as I work primarily on embedded systems...gadgets. I need to understand why the string pointer comes to an end when it is not being incremented.

因此在此代码中,您传递了一个指向字符串的指针,然后在此while循环中,您将计数器女巫加到了指针上,因此所访问的地址不断增加.我都知道了我的问题是为什么要完成?会发生什么,使得while循环评估为false并退出?在我看来,它似乎只是继续增加到一个int的大小,然后再次环绕.

so in this code here you pass in a pointer to a string and then in this while loop you increment the counter witch is added to the pointer so the address accessed keeps getting incremented. I get all that. My question is why does it finish? what happens such that the while loop evaluates to false and exits? to me it would seem to just keep on increment to the size of an int then wrap around again.

int string_length(char *s)
{
   int c = 0;

   while(*(s+c))
      c++;

   return c;
}

推荐答案

while(*(s+c))当遇到空字符并中断循环时会返回false

while(*(s+c)) returns false when the null character is encountered and breaks the loop

这篇关于使用指针的字符串长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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