我写了这段代码,但它给出的长度为0。我是初学者,找不到这有什么问题?这是我的代码:
#include <stdio.h>
#include <conio.h>
int strlgnth(char *s); /* func prototype */
int strlgnth(char *s)
{
int i;
{
for (i = 0; s[i] != '\0'; i++);
i = i++;
}
return i;
}
int main()
{
char s[1000], i, n;
printf("Enter a string: ");
scanf("%s", s);
{
i = strlgnth(s);
}
printf("Length of string: %d", n);
getch();
return 0;
}
最佳答案
您将计算结果分配给i
,但打印出n
。
此外,由于 n
从未被初始化,代码(也)会遇到未定义的行为,读取它以将其打印出来。
这一行
i=i++;
没用。
<小时/>分配strlgnth()
结果的值应该具有相同的类型,即int
。
或者更好的是使 strlgnth()
和所有 i
为 size_t
。
size_t
保证足够宽以容纳平台可能使用的任何尺寸。
最后这一行
scanf("%s", s);
很危险,因为它允许用户越过s
。为了避免这种情况,请告诉 scanf()
要扫描的最大字符数,即缓冲区的大小 - 1。备用的 1 个字符需要保存 0
-终结者:
scanf("%999s", s);
<小时/>
也许您应该清理源的布局。这可能有助于获得概览。
关于c - 不使用 strlen 和使用 C 中的函数来查找字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22129059/