how is char * to string literal valid?(char * 到字符串文字如何有效?)
问题描述
所以从我的理解指针变量指向一个地址.那么,以下代码在 C++ 中如何有效?
So from my understanding pointer variables point to an address. So, how is the following code valid in C++?
char* b= "abcd"; //valid
int *c= 1; //invalid
推荐答案
在 C 和非常旧的 C++ 版本中,字符串文字 "abcd" 的类型为 char[],一个字符数组.这样的数组自然会被 char* 指向,但不能被 int* 指向,因为那不是兼容的类型.
In C and very old versions of C++, a string literal "abcd" is of type char[], a character array. Such an array can naturally get pointed at by a char*, but not by a int* since that's not a compatible type.
但是,C 和 C++ 是不同的,通常是不兼容的编程语言.大约 20 年前,他们放弃了彼此的兼容性.
However, C and C++ are different, often incompatible programming languages. They dropped compatibility with each other some 20 years ago.
在标准 C++ 中,字符串文字的类型为 const char[],因此您发布的代码在 C++ 中均无效.这不会编译:
In standard C++, a string literal is of type const char[] and therefore none of your posted code is valid in C++. This won't compile:
char* b = "abcd"; //invalid, discards const qualifier
这将:
const char* c = "abcd"; // valid
这篇关于char * 到字符串文字如何有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:char * 到字符串文字如何有效?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
