初始化从指针生成整数而没有强制转换

我刚刚开始学习如何编程,我遇到了这样的错误:“初始化从指针生成整数而没有强制转换[默认启用]”有什么问题?

// This program pairs three kids with their favorite superhero #include  #include  main() { char Kid1[12]; // Kid1 can hold an 11-character name // Kid2 will be 7 characters (Maddie plus null 0) char Kid2[] = "Maddie"; // Kid3 is also 7 characters, but specifically defined char Kid3[7] = "Andrew"; // Hero1 will be 7 characters (adding null 0!) char Hero1 = "Batman"; // Hero2 will have extra room just in case char Hero2[34] = "Spiderman"; char Hero3[25]; Kid1[0] = 'K'; //Kid1 is being defined character-by-character Kid1[1] = 'a'; //Not efficient, but it does work Kid1[2] = 't'; Kid1[3] = 'i'; Kid1[4] = 'e'; Kid1[5] = '\0'; // Never forget the null 0 so C knows when the // string ends strcpy(Hero3, "The Incredible Hulk"); printf("%s\'s favorite hero is %s.\n", Kid1, Hero1); printf("%s\'s favorite hero is %s.\n", Kid2, Hero2); printf("%s\'s favorite hero is %s.\n", Kid3, Hero3); return 0; } 

 char Hero1 = "Batman"; 

应该

 char Hero1[] = "Batman"; 

有几次你有一些问题:

 #include  #include  main() { char Kid1[12]; // Kid1 can hold an 11-character name // Kid2 will be 7 characters (Maddie plus null 0) char Kid2[] = "Maddie"; // Kid3 is also 7 characters, but specifically defined char Kid3[7] = "Andrew"; // Hero1 will be 7 characters (adding null 0!) char *Hero1 = "Batman"; //needs to be a pointer // Hero2 will have extra room just in case char *Hero2 = "Spiderman"; //needs to be a pointer char Hero3[25] Kid1[0] = 'K'; //Kid1 is being defined character-by-character Kid1[1] = 'a'; //Not efficient, but it does work Kid1[2] = 't'; Kid1[3] = 'i'; Kid1[4] = 'e'; Kid1[5] = '\0'; // Never forget the null 0 so C knows when the // string ends strcpy(Hero3, "The Incredible Hulk"); printf("%s\'s favorite hero is %s.\n", Kid1, Hero1); printf("%s\'s favorite hero is %s.\n", Kid2, Hero2); printf("%s\'s favorite hero is %s.\n", Kid3, Hero3); return 0; } 

您应该在函数顶部定义所有变量,这是一个很好的C语法。

除此之外,我用评论标记了问题(并纠正了它们)。

问题是char Hero1 = "Batman"

  • 当您在代码中使用双引号字符串时,编译器会将其替换为指向字符串将在运行时驻留的内存空间的开头的指针。
  • 因此,通过char Hero1 = "Batman" ,您实际上是在尝试将一个内存地址(通常由32或64位数据组成,具体取决于您的系统)分配到一个字符变量(通常存储8位数据)。

要解决此问题,您需要将其更改为以下任一选项:

  • char Hero1[] = "Batman"
  • char* Hero1 = "Batman"

仅供参考,在上述两种情况下,字符串"Batman"将在运行时驻留在只读存储器部分中。

但是,这两种情况之间存在显着差异:

  • 使用char Hero1[] ,每次调用函数时, "Batman"字符串都将被复制到堆栈中。 Hero1数组将从该地址开始,您将能够在函数中稍后更改该数组的内容。
  • 使用char* Hero1 ,每次调用函数时, "Batman"字符串都不会被复制到堆栈中。 Hero1变量将指向字符串的原始地址,因此您将无法在函数内的任何位置更改该字符串的内容。

当从代码生成可执行映像时,该字符串将放在代码段中,该段是程序中的几个内存段之一。 然后,编译器用所谓的“整数赋值”替换所谓的“字符串赋值”。

例如, char* x = "abc"在编译为目标代码之前变为char* x = (char*)0x82004000 ,其中0x82004000是程序存储空间中字符串的(常量)地址。

当你执行sizeof("abc") ,可执行映像甚至不包含 "abc"字符串,因为没有对此字符串执行“运行时”操作。

没有为sizeof生成目标代码 – 编译器在编译期间计算此值,并立即用常量替换它。

您可以查看通常生成的(中间)映射文件,并查看该sizeof操作的输入字符串不会出现在任何位置。