c - 崩溃的 .exe 中的 strlen()

标签 c string.h

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);
}

关于c - 崩溃的 .exe 中的 strlen(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20789123/

相关文章:

c++ - <string.h> 还是 <string>?

c - 字符串打印额外值 C 编程

c - 从 freeRTOS 运行应用程序

c - c中替换头文件iostream.h

混淆缓冲区和 EOF 和 getchar

string-comparison - strcmp() 为相同的字符串比较返回不同的值

c++ - 加密给定的文本字符串 - 凯撒密码

c - gets() 和 getc() 有什么区别?

microcontroller - MPLABX/MPLAB IDE 中的 "File can not be opened"编译器错误

c - 程序执行输出