c - 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;
}
解决方案
继续我的评论,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)
如果您还有其他问题,请告诉我。
推荐阅读
- javascript - 如何删除过滤器中的空数组
- gitlab - 如何使用 VirtualBox 执行器设置 Gitlab-runner
- java - 方法参考 - 语法错误,插入“;” 完成 BlockStatements
- python - 电子商务网站是否需要在 django 中使用单独的身份验证系统?
- xaml - 如何更改标签上标签的背景颜色。但背景将在弯角 Xamarin.Forms
- c# - 继承时无法访问类字段
- elasticsearch - Elasticsearch,搜索以开头的单词
- php - 如何通过 cURL 正确地将 POST 请求发送到 REST API?
- scala - 从 trait 意外行为的案例类继承
- reactjs - 将图像的 URL 从 firebase 存储存储到 firebase 数据库 - URL 在网络空间中丢失