我刚刚开始学习如何编程,我遇到了这样的错误:“初始化从指针生成整数而没有强制转换[默认启用]”有什么问题?
// 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] = ' '; // 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] = ' '; // 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"
:
要解决此问题,您需要将其更改为以下任一选项:
仅供参考,在上述两种情况下,字符串"Batman"
将在运行时驻留在只读存储器部分中。
但是,这两种情况之间存在显着差异:
当从代码生成可执行映像时,该字符串将放在代码段中,该段是程序中的几个内存段之一。 然后,编译器用所谓的“整数赋值”替换所谓的“字符串赋值”。
例如, char* x = "abc"
在编译为目标代码之前变为char* x = (char*)0x82004000
,其中0x82004000
是程序存储空间中字符串的(常量)地址。
当你执行sizeof("abc")
,可执行映像甚至不包含 "abc"
字符串,因为没有对此字符串执行“运行时”操作。
没有为sizeof
生成目标代码 – 编译器在编译期间计算此值,并立即用常量替换它。
您可以查看通常生成的(中间)映射文件,并查看该sizeof
操作的输入字符串不会出现在任何位置。
以上就是c/c++开发分享初始化从指针生成整数而没有强制转换相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/519099.html