首页 > 解决方案 > C字符串长度错误

问题描述

我期望字符串长度为 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;
}

标签: cstrlen

解决方案


继续我的评论,4是一个很小的缓冲区,不要吝啬缓冲区的大小(即使如果一切顺利,它也会起作用)。迭代时,始终保护循环本身中的数组边界。在考虑字符串之前,您必须在字符串的最后一个字符s之后提供 nul 终止字符(例如,相当于 plain-old )'\0'0

注意上面的粗体字符。您将整数值分配为字符,这是行不通的。使用 将整数转换为 ASCII 数字+ '0'。请参阅ASCII 表和说明

总而言之,您将拥有:

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

#define MAXC 64

int main()
{
    int i = 0, N = 6;
    char s[MAXC];               /* always use a reasonable sized buffer */
    
    while (i < MAXC - 1 && N != 0) {        /* protect array bounds */
        int rem = N % 2;
        N = N/2;
        s[i] = rem + '0';       /* convert to ASCII digit */
        i++;
    }
    s[i] = 0;                   /* nul-terminate s */
    
    printf ("size = %zu (and i = %d)\n", strlen(s), i);

    return 0;
}

示例使用/输出

$ ./bin/mod2str
size = 3 (and i = 3)

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


推荐阅读