我写了这段代码,但是长度为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
-terminator:
scanf("%999s", s);
也许您应该清理源代码的布局。这可能有助于获得概述。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句