我在代码中不断收到错误“从字符串文字转换为char *”。代码的目的是使用指针指针为一个字分配string1和string2,然后将其打印出来。我怎样才能解决这个问题?
这是我的代码:
#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;
}
答案 0 :(得分:44)
C ++字符串文字是 const char
的数组,这意味着您无法合法地修改它们。
如果要安全地将字符串文字分配给指针(涉及隐式数组到指针的转换),则需要将目标指针声明为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;
}
如果语言没有强加此限制,请考虑会发生什么:
#include <iostream>
int main() {
char *ptr = "some literal"; // This is invalid
*ptr = 'S';
std::cout << ptr << "\n";
}
A(非const
)char*
允许您修改指针指向的数据。如果您可以将字符串文字(隐式转换为指向字符串的第一个字符的指针)分配给普通char*
,那么您将能够使用该指针修改字符串文字而不会出现编译器的警告。上面的无效代码如果有效,将打印
Some literal
- 它实际上可能在某些系统上这样做。但是,在我的系统上,它会因为分段错误而死机,因为它会尝试写入只读内存(不是物理ROM,而是被操作系统标记为只读的内存)。
(旁白:C的字符串文字规则与C ++的规则不同。在C中,字符串文字是char
的数组,不是 const char
的数组 - 但是尝试修改它有未定义的行为。这意味着在C中你可以合法地编写char *s = "hello"; s[0] = 'H';
,并且编译器不一定会抱怨 - 但是当你运行时,程序可能会因为分段错误而死亡这样做是为了保持与引入const
关键字之前编写的C代码的向后兼容性.C ++从一开始就有const
,因此不需要这种特殊的妥协。)