将字符串转换为字符数组

Converting a string to a character array

本文关键字:字符 数组 转换 字符串      更新时间:2023-10-16

我正在收到此错误

弃用从字符串常数到char*

的转换

我将如何将字符串放入字符阵列中。这是我尝试的:

char result[];
result = "invalid";

编辑:

这就是我要做的

bool intToRoman (int val, char result[])
{
   MAIN BODY
   result = "MMM";
}

在此功能中,我正在尝试将整数更改为罗马数字。在我的主体中,我想将字符串(例如" MMM")存储到我的角色阵列结果中。

您需要初始化数组:

char result[] = "invalid";

这将创建一个尺寸8数组char

但是,使用std::string

您可能会更好
std::string result("invalid");

如果您打算在运行时更改它,则可以使用以下任何选项:

       char result[] = "invalid"; // 8 bytes in the stack
static char result[] = "invalid"; // 8 bytes in the data-section

如果您不打算在运行时更改它,则可以使用以下任何选项:

       const char  result[] = "invalid"; // 8 bytes in the stack
static const char  result[] = "invalid"; // 8 bytes in the data-section
       const char* result   = "invalid"; // 8 bytes in the code-section, and a pointer (4 or 8 bytes) in the stack
static const char* result   = "invalid"; // 8 bytes in the code-section, and a pointer (4 or 8 bytes) in the data-section

如果您只想在运行时的稍后时间初始化它:

       char result[] = "invalid"; // 8 bytes in the stack
static char result[] = "invalid"; // 8 bytes in the data-section
...
strcpy(result,"MMM");
// But make sure that the second argument is not larger than the first argument:
// In the case above, the size of "MMM" is 4 bytes and the size of 'result' is 8 bytes