-2
#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 函数中工作?!提前致谢

4

2 回答 2

1

itoa写入第二个参数指向的内存。它本身并不分配该内存。这意味着您可以向它传递一个有效的内存指针。你不是; 你永远不会分配任何内存。它主要靠运气而不是设计起作用。

一种简单的方法是替换您定义op的行,char op[9];但请记住这是本地分配的内存,因此您无法从函数中返回它。

于 2013-11-18T11:42:39.313 回答
0

这是带有评论的修复

包括

#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;
}
于 2013-11-18T11:44:59.427 回答