简体   繁体   English

将 const char* 分配给 char*

[英]Assigning const char* to char*

#include <cstring>

char* str0;
const char* str1 = "abc";


// assign str1 to str0
strcpy(str0, str1);    // syntax correct, but run time error
str0 = str1;           // syntax error, cannot convert const char* to char*
string n_str = str1;
str0 = n_str;          // syntax error, cannot convert ...


cout << str0 << endl;  // expected output: abc

I'd like to make str0 same as str1 while runtime(after compilation), I don't know how to do it.我想在运行时(编译后)使 str0 与 str1 相同,我不知道该怎么做。 And for the case str0 = str1;对于str0 = str1; I don't understand why it won't work, because str0 points to nothing, while str1 points to a const string literal, so if I now make str0 point to what str1 is pointing to, it should be fine, but it is not.我不明白为什么它不起作用,因为 str0 指向任何内容,而 str1 指向一个 const 字符串文字,所以如果我现在让 str0 指向 str1 所指向的内容,应该没问题,但事实并非如此. So it there any way to solve it?那么有没有办法解决呢?

std::string str0;
const std::string str1 = "abc";

// assign str1 to str0
str0 = str1;

cout << str0 << endl;  // output: abc

If you insist on using C:如果你坚持使用C:

char* str0;
const char* str1 = "abc";

str0 = malloc(strlen(str1) + 1);
// if you use a c++ compiler you need instead:
// str0 = (char*) malloc(strlen(str1) + 1);

strcpy(str0, str1);

// and free after use
// if you use C++ this will not help much
// as pretty much any exception above will cause your code to get out of `free`,
// causing a memory leak
free(str0);

If you insist on using bad C++:如果你坚持使用糟糕的 C++:

char* str0;
const char* str1 = "abc";

str0 = new char[strlen(str1) + 1];

strcpy(str0, str1);

// and delete after use
// this will not help much
// as pretty much any exception above will cause your code to get out of `delete`,
// causing a memory leak
delete(str0);

Please read about RAII to understand why all of the solutions with manual memory management are bad: cppreference , wiki请阅读 RAII 以了解为什么所有手动内存管理的解决方案都不好: cppreference , wiki

Let's look one issue at a time让我们一次看一个问题

strcpy(str0, str1);

strcpy copies the characters pointed by str1 into the memory pointed by str0. strcpy将 str1 指向的字符复制到 str0 指向的内存中。 str1 points to "abc", but str0 doesn't point to anything, hence the runtime error. str1 指向“abc”,但 str0 不指向任何内容,因此出现运行时错误。 I would recommend using std::string everywhere so you don't have to manage the memory yourself.我建议在任何地方使用 std::string,这样您就不必自己管理内存。

str0 = str1;  

str0 is of type char*, str1 is of type const char*. str0 是 char* 类型,str1 是 const char* 类型。 The const qualifier instructs the compiler to not allow data modification on that particular variable (way over simplified role of const, for more in-depth explanation use your favorite search engine and you should be able to find a bunch of articles explaining const). const 限定符指示编译器不允许对该特定变量进行数据修改(超越 const 的简化作用,要获得更深入的解释,请使用您最喜欢的搜索引擎,您应该能够找到一堆解释 const 的文章)。 If you'd be able to assign the same pointer to str0 you'd break the const contract;如果您能够将相同的指针分配给 str0,您将违反 const 约定; str0 can be modifiable. str0 可以修改。

string n_str = str1;

This is valid because std::string overloads the assignment operator and accepts a const char pointer as the right hand value.这是有效的,因为 std::string 重载了赋值运算符并接受一个 const char 指针作为右手值。

str0 = n_str;

n_str is of type std::string and str0 is char*, there's no overloaded operator that allows this. n_str 是 std::string 类型,str0 是 char*,没有重载运算符允许这样做。 If you really want the raw point out of an std::string you can use the c_str() method and it will return you a const char* - I strongly advise against it, unless you have to pass it to a function that only accepts const char*.如果你真的想要一个 std::string 的原始点,你可以使用 c_str() 方法,它会返回一个 const char* - 我强烈建议不要这样做,除非你必须将它传递给一个只接受的函数常量字符*。

Copying strings is an expensive operation.复制strings是一项昂贵的操作。 But moving strings from one place to another is efficient.但是将strings从一个地方移动到另一个地方是有效的。

casts away the const抛弃const

str0 = (char*) str1;

or use std::string class template library for managing strings.或使用std::string类模板库来管理字符串。 std::string owns the character buffer that stores the string value. std::string拥有存储字符串值的字符缓冲区。 characters are part of the string object.字符是string对象的一部分。 cont char* stores the address of such a character buffer but does not own it. cont char*存储这样一个字符缓冲区的地址,但不拥有它。

c_str returns a const char* that points to a null-terminated string. c_str返回一个指向以空字符结尾的字符串的const char* It is useful when you want to pass the contents.当您想传递内容时,它很有用。

std::string str1 = "abc";
char* str0;

strcpy(str0, str1.c_str());
printf(str0);

const is part of the type, and as such, you can cast it "away". const是类型的一部分,因此,您可以将其“扔掉”。 This is considered bad practice, but you should think of const as a strong suggestion of the original programmer, not to modify it.这被认为是不好的做法,但您应该将const视为原始程序员的强烈建议,而不是修改它。

const char * str1 = "abc";
char * str2 = (char*) str1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM