它不会返回int或者什么东西吗? 这是我的代码片段:
int wordlength(char *x);
int main()
{
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
printf("Word Length: %d", wordlength(word));
return 0;
}
int wordlength(char *x)
{
int length = strlen(x);
return length;
}
答案 0 :(得分:1)
更改此部分:
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
为:
char word[256]; // you need a string here, not just a single character
printf("Enter a word: \n");
scanf("%255s", word); // to read a string with scanf you need %s, not %c.
// Note also that you don't need an & for a string,
// and note that %255s prevents buffer overflow if
// the input string is too long.
如果您启用了警告(例如gcc -Wall ...
),您还应该知道编译器会帮助您解决大多数这些问题
char sentence[256];
printf("Enter a sentence: \n");
fgets(sentence, sizeof(sentence), stdin);
答案 1 :(得分:1)
函数strlen
应用于具有终止零的字符串(字符数组)。您正在将该函数应用于指向单个字符的指针。所以程序有不确定的行为。