字符串指针和字符串数组

字符串指针和字符串数组

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

问题描述

在以下代码中

char str [] =" asdf" ;

str [0] ='s'';

是可能的。


但是char * str =" ASDF" ;

str [0] ='s'';

是运行时错误。


我理解的是什么是* str =" asdf"存储在只读存储器中。

as str []存储在堆栈中。


有没有更好的解释呢?

In following code
char str[] = "asdf" ;
str[0] = ''s'' ;
is possible.

But char *str = "asdf" ;
str[0] = ''s'' ;
is an run-time error.

What i understand is *str = "asdf" is stored in Read-only-Memory. Where
as str[] is stored in stack.

Does any body has any better explanation for that?

推荐答案




str [ ]是数据的副本asdf

* str指向asdf本身。



str[] is a copy of the data "asdf"
*str points to "asdf" itself.




str []是副本数据asdf
* str指向asdf本身。



str[] is a copy of the data "asdf"
*str points to "asdf" itself.




除此之外,还有未定义的行为要修改

a string litteral - 这就是他在指针

case。



And in addition to that, it''s undefined behavior to modify
a string litteral - which is what he did in the pointer
case.





它是不允许更新字符串文字,因此如果你这样做,可能会发生任何
。有些机器会崩溃,有些机器会改变字面值,有些机器会覆盖[伪]随机内存,有些会写诽谤性电子邮件

给你当地的国家元首。 />

有些实现有一个堆栈,但是`str []`不需要在它上面。

有些实现有只读内存,但是"不需要在其中。


但是不允许更新字符串文字。


-

克里斯尝试,或尝试不 - 没有做 Dollin



It is Not Allowed to update string literals, so if you do it, anything
may happen. Some machines will crash, some will alter the literal, some
will overwrite [pseudo] random memory, some will write libellous emails
to your local head of state.

Some implementations have a stack, but `str[]` need not be on it.
Some implementations have read-only memory, but "" need not be in it.

But it is Not Allowed to update string literals.

--
Chris "try, or try not -- there is no do" Dollin


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

07-31 02:49