【发布时间】:2022-02-19 03:47:34
【问题描述】:
我是 C++ 新手。尽管已经提出并回答了许多类似的问题,但我仍然觉得这些概念令人困惑。 我知道
char c='a' // declare a single char c and assign value 'a' to it
char * str = "Test"; // declare a char pointer and pointing content str,
// thus the content can't be modified via point str
char str1[] = "Test"; // declare a char array str1 and assign "Test" to it
// thus str1 owns the data and can modify it
我的第一个问题是char * str 创建了一个指针,char * str = "Test"; 是如何工作的?将字符串文字分配给指针?尽管它完全合法,但对我来说没有意义,我认为我们只能将地址分配给指针,但是 "Test" 是字符串文字而不是地址。
第二个问题是为什么下面的代码连续两次打印出“Test”?
char str2[] = {'T','e','s','t'}; // is this line legal?
// intializing a char array with initilizer list, seems to be okay to me
cout<<str2<<endl; // prints out "TestTest"
为什么cout<<str2<<endl; 会打印出“TestTest”?
【问题讨论】:
-
@FrançoisAndrieux 对于
char * str = "Test";,在 Clion 中,它甚至没有发出警告,在 ubuntu 终端中,编译器发出警告说warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings],但它仍然运行良好。我的 g++ 是 9.3.0 -
回复:“为什么
cout<<str2<<endl;打印出“TestTest”?”,这是Printing char arrays c++ 的副本 -
有时最好使用在线编译器检查您的代码,例如ideone,看看您是否得到相同的结果。你甚至可以在这里分享它
标签: c++