有人可以告诉我这个代码有什么问题吗?
Can someone please tell me what's wrong with this code?
#include <iostream>
#include <stdlib.h>
#include <string>
#include<string.h>
#include <stdio.h>
using namespace std;
void OpCode()
{
string mnemonic;
int hex;
char *op;
cout << "Entre mnemonic : ";
cin >> mnemonic;
char *str1 = strdup(mnemonic.c_str());
if(strcmp(str1, "ADD") == 0)
{
hex = 24;
itoa(hex,op,16);
cout << op;
cout << "nEqual";
}
else
cout << "nFalse";
}
int main()
{
OpCode();
return 0;
}
它一直运行到我使用 op 变量的部分,我尝试在 main 函数中复制和粘贴它工作得很好,为什么它在 OpCode 函数中不起作用?!提前致谢
itoa
写入其第二个参数指向的内存。它本身不会分配该内存。这意味着由您为其传递有效的内存指针。你不是;您从不分配任何内存。它主要靠运气而不是设计工作。
一个简单的方法是替换定义op
的行char op[9];
但请记住,这是本地分配的内存,因此您无法从函数中返回它。
这是带有注释的修复程序
包括
#include <stdlib.h>
#include <string>
#include<string.h>
#include <stdio.h>
using namespace std;
void OpCode()
{
string mnemonic;
int hex;
char op[10]; // allocate a pointer op that points to 10 empty spaces of type char.
cout << "Entre mnemonic : ";
cin >> mnemonic;
char *str1 = strdup(mnemonic.c_str());
if(strcmp(str1, "ADD") == 0)
{
hex = 24;
itoa(hex,op,16); // convert hex to an ASCII representation and write the ASCII to the 10 empty spaces we allocated earlier.
cout << op;
cout << "nEqual";
}
else
cout << "nFalse";
free (str1); // free the memory that was allocated using strdup so you do not leak memory!
}
int main()
{
OpCode();
return 0;
}
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了