每當遇到處理c字符串的情況,我都很困惑。C++語言中字符串重複的混淆
爲什麼這兩個打印有相同的結果? 在我的說明中,第一個函數將字符串的地址賦給文本變量。這對我來說似乎是適當的。但第二個函數在文本變量指向的地方分配地址。這裏發生了什麼?
#include <iostream>
#include <cstring>
void getText(char** text) {
*text = strdup("AAAAA");
}
void getText2(char* text) {
text = strdup("AAAAA");
}
int main()
{
char* text;
getText(&text);
std::cout << text << std::endl; // prints "AAAAA"
getText2(text);
std::cout << text << std::endl; // prints "AAAAA"
}
這不是C ..應該先清除這個混淆。 –
只要不在C++中使用C字符串,就永遠不會有問題。 –
第二個函數不會修改'main'的'char * text' – UnholySheep