[英]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
我想在運行時(編譯后)使 str0 與 str1 相同,我不知道該怎么做。 對於str0 = str1;
我不明白為什么它不起作用,因為 str0 指向任何內容,而 str1 指向一個 const 字符串文字,所以如果我現在讓 str0 指向 str1 所指向的內容,應該沒問題,但事實並非如此. 那么有沒有辦法解決呢?
std::string str0;
const std::string str1 = "abc";
// assign str1 to str0
str0 = str1;
cout << str0 << endl; // output: abc
如果你堅持使用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);
如果你堅持使用糟糕的 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);
請閱讀 RAII 以了解為什么所有手動內存管理的解決方案都不好: cppreference , wiki
讓我們一次看一個問題
strcpy(str0, str1);
strcpy將 str1 指向的字符復制到 str0 指向的內存中。 str1 指向“abc”,但 str0 不指向任何內容,因此出現運行時錯誤。 我建議在任何地方使用 std::string,這樣您就不必自己管理內存。
str0 = str1;
str0 是 char* 類型,str1 是 const char* 類型。 const 限定符指示編譯器不允許對該特定變量進行數據修改(超越 const 的簡化作用,要獲得更深入的解釋,請使用您最喜歡的搜索引擎,您應該能夠找到一堆解釋 const 的文章)。 如果您能夠將相同的指針分配給 str0,您將違反 const 約定; str0 可以修改。
string n_str = str1;
這是有效的,因為 std::string 重載了賦值運算符並接受一個 const char 指針作為右手值。
str0 = n_str;
n_str 是 std::string 類型,str0 是 char*,沒有重載運算符允許這樣做。 如果你真的想要一個 std::string 的原始點,你可以使用 c_str() 方法,它會返回一個 const char* - 我強烈建議不要這樣做,除非你必須將它傳遞給一個只接受的函數常量字符*。
復制strings
是一項昂貴的操作。 但是將strings
從一個地方移動到另一個地方是有效的。
拋棄const
str0 = (char*) str1;
或使用std::string
類模板庫來管理字符串。 std::string
擁有存儲字符串值的字符緩沖區。 字符是string
對象的一部分。 cont char*
存儲這樣一個字符緩沖區的地址,但不擁有它。
c_str
返回一個指向以空字符結尾的字符串的const char*
。 當您想傳遞內容時,它很有用。
std::string str1 = "abc";
char* str0;
strcpy(str0, str1.c_str());
printf(str0);
const
是類型的一部分,因此,您可以將其“扔掉”。 這被認為是不好的做法,但您應該將const
視為原始程序員的強烈建議,而不是修改它。
const char * str1 = "abc";
char * str2 = (char*) str1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.