char * 到字符串文字如何有效? [英] how is char * to string literal valid?

查看:22
本文介绍了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 * 到字符串文字如何有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆