我计算字符串长度的函数产生了一个非常大的数字,我不知道为什么。
int string_length (char *s)
{
for(k=0; s[k] != '\0'; k++);
return k;
}
string_length (source);
printf("String length: %d \n", source);
Enter string: ew
String length: 1430575920
应该不使用strlen()
。
答案 0 :(得分:2)
您不应在此处打印source
printf("String length: %d \n", source);
尝试打印string_length()
函数的返回值。例如
size_t ret = string_length (source);/* since predefined strlen() return type is of size_t type, so use size_t as ret type */
printf("String length: %zu \n", ret);
甚至更好
printf("String length: %zu \n", string_length(source));
例如
size_t string_length (char *s) { /*since predefined strlen() return type is of size_t type */
for(size_t k=0; s[k] != '\0'; k++);
return k;
}