C++ 不推荐将字符串文字转换为字符*
我的代码中不断出现错误“从字符串文字到字符*的转换已弃用”。代码的目的是使用指向指针的指针为string1和string2分配一个单词,然后将其打印出来。我怎样才能解决这个问题 这是我的密码:C++ 不推荐将字符串文字转换为字符*,c++,string,char,C++,String,Char,我的代码中不断出现错误“从字符串文字到字符*的转换已弃用”。代码的目的是使用指向指针的指针为string1和string2分配一个单词,然后将其打印出来。我怎样才能解决这个问题 这是我的密码: #include <iostream> using namespace std; struct WORDBLOCK { char* string1; char* string2; }; void f3() { WORDBLOCK word; word.st
#include <iostream>
using namespace std;
struct WORDBLOCK
{
char* string1;
char* string2;
};
void f3()
{
WORDBLOCK word;
word.string1 = "Test1";
word.string2 = "Test2";
char *test1 = word.string1;
char *test2 = word.string2;
char** teststrings;
teststrings = &test1;
*teststrings = test2;
cout << "The first string is: "
<< teststrings
<< " and your second string is: "
<< *teststrings
<< endl;
}
#包括
使用名称空间std;
结构字块
{
字符*string1;
字符*string2;
};
void f3()
{
字块词;
word.string1=“Test1”;
word.string2=“Test2”;
char*test1=word.string1;
char*test2=word.string2;
字符**测试字符串;
teststrings=&test1;
*teststrings=test2;
coutC++字符串文本是constchar
的数组,这意味着您不能合法地修改它们
如果要安全地将字符串文本分配给指针(这涉及隐式数组到指针的转换),则需要将目标指针声明为const char*
,而不仅仅是char*
以下是编译时不会出现警告的代码版本:
#include <iostream>
using namespace std;
struct WORDBLOCK
{
const char* string1;
const char* string2;
};
void f3()
{
WORDBLOCK word;
word.string1 = "Test1";
word.string2 = "Test2";
const char *test1 = word.string1;
const char *test2 = word.string2;
const char** teststrings;
teststrings = &test1;
*teststrings = test2;
cout << "The first string is: "
<< teststrings
<< " and your second string is: "
<< *teststrings
<< endl;
}
--但在我的系统上,由于它试图写入只读内存(不是物理ROM,而是被操作系统标记为只读的内存),它会因分段错误而死亡
(旁白:C的字符串文字规则不同于C++的规则。在C中,字符串文字是char
的数组,而不是const char
——但试图修改它有未定义的行为。这意味着在C中,您可以合法地编写char*s=“hello”;s[0]=“h”;,编译器不一定会抱怨,但是程序运行时可能会出现分段错误。这是为了保持与C++代码之间的向后兼容性。在代码< > const 关键字被引入。C++从一开始就有了<代码> const < /> >,所以这个特殊的妥协不是。(没有必要。)这是难以置信的清晰、足智多谋和启发性的。感谢您的帮助,我现在理解得更好了!解释很好,但代码不清楚且令人困惑-看起来您希望在实际打印TestString值时打印“Test1”和“Test2”(指向test1
)的偏移量和test1
指向的字符串(这是“Test2”,因为您通过teststrings修改了test1
)@neuviemeporte:(我知道我回复有点晚。)我所做的只是在OP的代码中添加所需的const
关键字。我没有尝试进行任何其他更正或改进。你不是说“不是一个const char数组--”即使C++中的字符串文字从C++开始是 CONST ,C++ 03和更早似乎有一个隐式转换为“代码> char */COD>”。
#include <iostream>
int main() {
char *ptr = "some literal"; // This is invalid
*ptr = 'S';
std::cout << ptr << "\n";
}