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
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01