指针在C常量字符串 [英] Pointer to const string in C

查看:149
本文介绍了指针在C常量字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char *p = "string"; //creates pointer to constant string

char p[] = "string"; //just an array with "string"

我只是有点困惑为什么它在第一个例子创建一个指向一个字符串常量?难道不应该只是一个指针指的是一个地方在内存中串?

I'm just a bit confused about why does it in the first example create a pointer to a constant string? Shouldn't it be just a pointer refering to a place in memory with "string"?

推荐答案

这是在C不幸的法律(和C ++ 03的兼容性)。但是,任何企图通过指针修改字符串会导致不确定的行为。因此,最好始终指定字符串到为const char *

It is unfortunately legal in C (and in C++03, for compatibility). But any attempt to modify the string literal via the pointer will result in Undefined behavior. So, better always assign the string literal to a const char*

const char * cp = "Hello"; //OK
char* p = "Hello"; //OK (unfortunately)
cp[0] = 'Y'; //Compile-time error, good
p[0] = 'Y'; //no compiler error, undefined behavior

这篇关于指针在C常量字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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