从 char 指针更改索引处的 char
我知道以下内容无效:
char *string = "Some String":
string[1] = 'v';//INVALID
但是,在不将字符串类型更改为某种字符数组的情况下,如何在此处实现所需的行为?
字符串中的最终值应该是“Svme String”
I know that the following is invalid:
char *string = "Some String":
string[1] = 'v';//INVALID
But how can I achieve the desired behavior here, without changing the type of string to some sort of char array?
The final value in string should be 'Svme String'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一种情况下,这两件看起来几乎相同的东西
大不相同
,占据了一个指针的大小(32或64位)。该指针设置为指出由编译器分配的文字字符串,几乎可以肯定在仅读取的存储区域中,通常在执行代码所在的同一组内存块中。这就是为什么修改字符串不起作用的原因(在大多数系统上),您正在尝试
在第二个案例StringArr中仅读取的内存区域中修改某些内容,占12个字节。编译器将安排从字面的“一些字符串”中加载这12个字节。何时以及如何完成此操作取决于声明弦乐的位置。
如果这样的话,
那么当功能启动时,将保留12个字节,并将文字复制到它们中。每次调用此功能时,都会发生这种情况。
如果是这样的
,
则编译器将在程序静态数据区域(存储全球群体)中分配12个字节,并通常在编译过程中将文字加载到该内存中,或者可能在程序启动时,但仅完成一次。它在可写的记忆领域
These two things that look almost identical
are very different
in the first case stringLit occupies the size of one pointer (32 or 64 bits). This pointer is set to point at a literal string allocated by the compiler almost certainly in a memory area that is read only , usually in the same set of memory chunks where the execution code is. This is why modifying the string doesnt work (on most systems), you are trying to modify something in a read only memory area
In the second case stringArr occupies 12 bytes. The compiler will arrange for those 12 bytes to be loaded from the literal "Some String". When and how this is done depends on where stringLit is declared.
If its like this
then 12 bytes will be reserved in the stack when the function starts and the literal will be copied into them. This will happen every time this function is called.
If its like this
or
then the compiler will allocate 12 bytes in the programs static data area (where globals are stored) and usually load the literal into that memory during compilation, or perhaps when the program starts, but its only done once. And it is in a writable area of memory
唯一的方法是将字符串文字存储在字符数组中,然后您可以使用指针到数组来更改存储的字符串。
例如
或
The only way is to store the string literal in a character array and then you can use a pointer to the array to change the stored string.
For example
or