Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C字符串长度出错_C_Strlen - Fatal编程技术网

C字符串长度出错

C字符串长度出错,c,strlen,C,Strlen,我希望字符串长度为4,但当我执行strlen()时,它将变为0。编译过程中没有错误。 我无法理解这背后的原因 以下是我的代码片段: #include <stdio.h> #include <string.h> int main() { int N = 6; char s[4]; int i = 0; while(N!=0) { int rem = N%2; N = N/2; //printf

我希望字符串长度为4,但当我执行
strlen()
时,它将变为0。编译过程中没有错误。 我无法理解这背后的原因

以下是我的代码片段:

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

int main()
{
    int N = 6;
    char s[4];
    int i = 0;
    while(N!=0) {
        int rem = N%2;
        N = N/2;
        //printf("%d\n", rem);
        s[i] = rem;
        i++;
    }
    //s[0] = 1;
    printf("size = %zu", strlen(s));

    return 0;
}
#包括
#包括
int main()
{
int N=6;
chars[4];
int i=0;
而(N!=0){
int rem=N%2;
N=N/2;
//printf(“%d\n”,rem);
s[i]=rem;
i++;
}
//s[0]=1;
printf(“大小=%zu”,strlen);
返回0;
}

继续我的评论,
4
是一个很小的缓冲区,不要吝啬于缓冲区大小(即使如果一切顺利,它也会工作)。迭代时,始终在循环本身中保护数组边界。在考虑<代码> s>代码>字符串之前,必须在字符串中的最后一个<强>字符< /强>之后提供NUL终止字符(例如<代码> > 0”<代码>,相当于“原始代码> 0代码>代码>

请注意上面的粗体字符。您正在将整数值指定为字符,这将不起作用。使用
+“0”
将整数转换为ASCII数字。看

总而言之,你应该:

#包括
#包括
#定义MAXC 64
int main()
{
int i=0,N=6;
char s[MAXC];/*始终使用大小合理的缓冲区*/
而(i
示例使用/输出

$。/bin/mod2str
尺寸=3(i=3)

如果您还有其他问题,请告诉我。

哇!您可以在哪里终止
s
,并且永远不要忽略缓冲区大小<代码>字符s[64]
一起使用更有意义,而(i<63&&N!=0){…
可以保护数组边界--在退出循环后为
'\0'
保留1个字符,使用
s[i]=0;
。。