char * 到字符串文字如何有效?

2022-01-18 00:00:00 initialization pointers c c++

所以从我的理解指针变量指向一个地址.那么,以下代码在 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

相关文章