【问题标题】:strlen() not giving right value? [closed]strlen() 没有给出正确的值? [关闭]
【发布时间】:2013-09-27 20:12:59
【问题描述】:
#include "stdafx.h"
#include<string.h>
#include<stdio.h>


int _tmain(int argc, _TCHAR* argv[])
{

    char abc[28] ;
    //abc[26] = '\0';
    abc[0]=65;
    char hj = abc[0];
    for(int i=0; i<26; i++)
    {
    abc[i]=++hj;

    printf("%d\n",i);

    }
    int l=strlen(abc);
    abc[l]='\0';
    printf("length of abc_array is %d\n",(strlen(abc)));
    for(int i=0; i<strlen(abc); i++)
    {
    printf("%c",abc[i]);
    printf("\n");
    }

}

字符串的输出长度是39,这是错误的。错误是什么?

【问题讨论】:

  • strlen 需要一个空值。您不能使用它来确定将 null 放在何处。
  • 这与 C++ 有什么关系?这显然是一道 C 题。
  • 你的评论部分//abc[26] = '\0';是正确的,取消评论
  • 这个问题似乎是题外话,因为它只是基于根本不阅读文档。

标签: c strlen


【解决方案1】:

你需要在调用strlen之前设置abc[i] = '\0'

【讨论】:

    【解决方案2】:

    标准strlen 函数只适用于字符串。字符串是由零字符终止的字符序列。将不是字符串的内容传递给 strlen 会导致未定义的行为。

    您在代码中传递给strlen 的不是字符串。这就是为什么你从strlen 得到毫无意义的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多