int main()
{
int LengthofWord = strlen('word');
printf("%s", LengthofWord);
}
由于某种原因,此代码正在崩溃。我想检索一个字符串(在本例中为字符串)的长度以供以后使用。为什么这段代码会崩溃?
谢谢
您的代码存在以下问题:
'word'
。该'
符号用于单个字符,例如'a'
。你的意思是写"word"
。LengthofWord
应该是size_t
而不是int
因为那是strlen
返回的。printf
。您使用%s
了适合字符串的哪个。对于整数值,您应该使用%zu
. 虽然,请注意某些运行时不会理解%zu
.int main(void)
所以你的完整程序应该是:
#include <stdio.h>
#include <string.h>
int main(void)
{
size_t LengthofWord = strlen("word");
printf("%zu", LengthofWord);
}
它应该是
... = strlen("word");
在 C 中,字符串文字放在双引号中。
也不strlen()
返回。_ 所以整行应该是这样的:size_t
int
size_t LengthofWord = strlen("word");
最后打印出size_t
使用转换说明符“zu”:
printf("%zu", LengthofWord);
A"%s"
需要一个以为结尾的0
数组char
,一个“字符串”。
最后同样重要的是,使用
int main(void)
{
...
并通过返回一个来完成它int
...
return 0;
}
'
C中的quote和quote之间有区别"
。使用字符串"
。
改变
int LengthofWord = strlen('word');
^ ^
| |
-----------Replace these single quotes with double quotes("")
至
int LengthofWord = strlen("word");
strlen
返回size_t
类型。将其声明为size_t
type 而不是int
. printf
还要更改to中的格式说明符%zu
printf("%d", LengthofWord);
您的最终代码应如下所示
int main(void)
{
size_t LengthofWord = strlen('word');
printf("%zu", LengthofWord);
return 0;
}