字符串文字:它们去哪里了? [英] String literals: Where do they go?

查看:55
本文介绍了字符串文字:它们去哪里了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在哪里分配/存储字符串文字感兴趣.

I am interested in where string literals get allocated/stored.

我确实找到了一个有趣的答案

I did find one intriguing answer here, saying:

内联定义一个字符串实际上会将数据嵌入程序本身,并且不能更改(某些编译器通过巧妙的技巧允许这样做,不要打扰).

Defining a string inline actually embeds the data in the program itself and cannot be changed (some compilers allow this by a smart trick, don't bother).

但是,它与C ++有关,更不用说它不打扰了.

But, it had to do with C++, not to mention that it says not to bother.

我很烦. = D

所以我的问题是我的字符串文字在哪里以及如何保存?为什么我不应该尝试更改它?实施会因平台而异吗?有人愿意详细说明智能技巧"吗?

So my question is where and how is my string literal kept? Why should I not try to alter it? Does the implementation vary by platform? Does anyone care to elaborate on the "smart trick?"

推荐答案

一种常见的技术是将字符串文字放入只读数据"部分,该部分将以只读方式映射到进程空间(即为什么您不能更改它.)

A common technique is for string literals to be put in "read-only-data" section which gets mapped into the process space as read-only (which is why you can't change it).

它确实因平台而异.例如,较简单的芯片体系结构可能不支持只读内存段,因此数据段将是可写的.

It does vary by platform. For example, simpler chip architectures may not support read-only memory segments so the data segment will be writable.

然后尝试找出使字符串文字可变的技巧(它将高度依赖于您的平台,并且可能会随着时间而改变),只需使用数组即可:

Rather then try to figure out a trick to make string literals changeable (it will be highly dependent on your platform and could change over time), just use arrays:

char foo[] = "...";

编译器将安排从字面量初始化数组,您可以修改数组.

The compiler will arrange for the array to get initialized from the literal and you can modify the array.

这篇关于字符串文字:它们去哪里了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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