在C ++中创建可修改的字符串文字 [英] Create a modifiable string literal in C++
问题描述
是否可以在C ++中创建可修改的字符串文字?例如:
Is it possible to create a modifiable string literal in C++? For example:
char* foo[] = {
"foo",
"foo"
};
char* afoo = foo[0];
afoo[2] = 'g'; // access violation
这会产生访问冲突,因为foo分配在只读存储器(我相信.rdata节)。有什么办法强制foo进入可写内存(.data部分)?即使通过pragma也是可以接受的! (Visual Studio编译器)
This produces an access violation because the "foo"s are allocated in read only memory (.rdata section I believe). Is there any way to force the "foo"s into writable memory (.data section)? Even via a pragma would be acceptable! (Visual Studio compiler)
我知道我可以做strdup和一些其他的东西来解决这个问题,但我想知道如果我能做已问。 :)
I know I can do strdup and a number of other things to get around the problem, but I want to know specifically if I can do as I have asked. :)
推荐答案
您可以创建一个多维数组的字符:
You could create a multidimensional array of chars:
#include <iostream>
int main(int argc, char** argv)
{
char foo[][4] = {
"foo",
"bar"
};
char* afoo = foo[0];
afoo[2] = 'g';
std::cout << afoo << std::endl;
}
更详细的方式来定义数组:
More verbose way to define the array:
char foo[][4] = {
{'f', 'o', 'o', '\0'},
{'b', 'a', 'r', '\0'}
};
这篇关于在C ++中创建可修改的字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!