2014-01-23 26 views
-3

我得到这个错误转换一个字符串的字符数组

从字符串常量弃用转换为char*

我将如何把字符串转换成字符数组。这里是我的尝试:

char result[]; 
result = "invalid"; 

编辑:

这就是我想要做的

bool intToRoman (int val, char result[]) 
{ 
    MAIN BODY 
    result = "MMM"; 
} 
在这个函数

我试图改变一个整数到罗马数字。在我的主体中,我想将我的字符串(例如“MMM”)存储到我的字符数组结果中。

+5

由于这是C++:'的std :: string结果( “无效”);' – Borgleader

+0

分配?不能使用'std :: string'? –

+0

'strncpy()'为你的情况呢?再次:使用'std :: string'使[tag:C++]更简单! –

回答

1

如果您打算在运行时改变它,那么你可以使用任何下列选项:

 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 
+0

我编辑我的帖子。 – user3229707

+0

我编辑了我的答案... –

+0

k谢谢,不妨在这里再问你一个问题。如果我有一个字符串罗马=“MMM”。我怎么把罗马里的东西放到结果 – user3229707

8

您需要初始化数组:

char result[] = "invalid"; 

这将创建一个大小为8阵列的char

但是你可能会更好使用std::string

std::string result("invalid"); 
+0

* ahem * s/of/off /? – Borgleader

+1

@Borgleader谢谢。我真的应该学会打字这些天。 – juanchopanza

+0

这不是我打算做的。我试图声明一个数组,然后稍后在代码体中有人将数组中的单词无效。 – user3229707

相关问题