zoukankan      html  css  js  c++  java
  • 关于strlen函数的一个问题

    最近有个同学给了我一个这样的程序:

    #include <stdio.h>
    #include <string.h>

    int main(int argc, const char *argv[])
    {
    char a[10] = "abcde";
    char b[] = "abcdef";

    if(strlen(a) - strlen(b) >= 0)
       printf("a > b ");
    else 
    printf("a < b ");
    return 0;
    }


    输出是: a > b


    这让大家很不解。先加了一些printf语句

    #include <stdio.h>
    #include <string.h>


    int main(int argc, const char *argv[])
    {
    char a[10] = "abcde";
    char b[] = "abcdef";
    printf("%d ",strlen(a) - strlen(b));
    printf("%d ",strlen(a));
    printf("%d ",strlen(b));
    if((int)(strlen(a) - strlen(b)) >= 0)
       printf("a > b ");
    else 
    printf("a < b ");
    return 0;
    }

    输出是:-1

    5

    6

    a > b

    还是没有发现问题


    接着,我就开始怀疑strlen函数的问题了。

    man了一下strlen函数,发现它的返回值是size_t   是unsigned int 的一个别名

    所以一切豁然开朗。在strlen(a) -strlen(b) > 0的计算过程中,都转换成无符号整型值了,故strlen(a) -strlen(b) = -1 变成了最大的整数值ffffffff > 0 为真

    然后做出了下列解决方案:

    #include <stdio.h>
    #include <string.h>


    int main(int argc, const char *argv[])
    {
    char a[10] = "abcde";
    char b[] = "abcdef";
    printf("%d ",(int)(strlen(a) - strlen(b)) >= 0);
    printf("%d ",strlen(a));
    printf("%d ",strlen(b));
    if((int)(strlen(a) - strlen(b)) >= 0)
       printf("a > b ");
    else 
    printf("a < b ");
    return 0;
    }

    输出为:

    0

    5

    6

    a < b


    如有问题,请大家指正。

  • 相关阅读:
    数据库索引的作用和长处缺点
    ping不通的几种可能原因
    UVA
    strtok、strtok_s、strtok_r 字符串切割函数
    CheckBoxPreference组件
    EM算法原理
    Android中ExpandableListView控件基本使用
    拓扑排序的原理及事实上现
    DropdownList绑定的两种方法
    leetcode第一刷_Length of Last Word
  • 原文地址:https://www.cnblogs.com/vonyao/p/3614337.html
Copyright © 2011-2022 走看看