【问题标题】:understand how char works in c++ [duplicate]了解 char 在 C++ 中的工作原理 [重复]
【发布时间】: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&lt;&lt;str2&lt;&lt;endl; 会打印出“TestTest”?

【问题讨论】:

标签: c++


【解决方案1】:

char * str = "Test"; 在 C++ 中是不允许的。字符串文字只能由指向const 的指针指向。你需要const char * str = "Test";

如果您的编译器接受char * str = "Test";,则它可能已过时。自 C++11(10 多年前问世)以来,就不允许这种转换。


char * str = "Test";工作吗?

字符串文字可以隐式转换为指向文字开头的指针。在 C++ 中,数组可以隐式转换为指向其第一个元素的指针。例如int x[10] 可隐式转换为int*,转换结果为&amp;(x[0])。这适用于字符串文字,它们的类型是一个 const 字符数组 (const char[])。


下面的代码怎么会连续两次打印出“Test”?

在 C++ 中,与字符串相关的大多数功能都假定字符串以空值结尾,这在字符串文字中是隐含的。您需要将{'T','e','s','t','\0'} 等同于"Test"

【讨论】:

  • char * str = "Test"; 似乎在任何地方都可以接受,这里也是ideone.com/l/cpp,没有错误或警告,我的 g++ 和 gcc 是 9.3.0。这是过时的吗?
  • @AlbertGLieu 自 C++11 以来一直不允许。请参阅String Literal:“字符串文字不可转换或分配给非常量 CharT*。如果需要这种转换,则必须使用显式转换(例如 const_cast)。(自 C++11 起)”这不是我的意见,实际上语言不允许。默认情况下,即使 gcc 9.3.0 也会产生警告,因此您的配置必须将其静音:godbolt.org/z/aG54csajr
  • @François Andrieux 非常感谢您分享知识和宝贵的时间。
  • @AlbertGLieu GCC 提供了很多默认启用的非标准扩展。它将允许 C++ 中通常不允许的各种代码编译和运行,但它使代码不可移植(你有 GCC C++ 代码,而不是 C++ 代码)。最臭名昭著的可能是可变长度数组。我建议使用编译标志 -pedantic-Werror 禁用这些扩展。
猜你喜欢
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
  • 2017-03-20
  • 2017-09-20
  • 1970-01-01
  • 2017-03-04
  • 2013-07-10
  • 2019-07-25
相关资源
最近更新 更多