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

查看:68
本文介绍了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天全站免登陆