为字符串分配内存 [英] Allocating memory for strings

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

问题描述

大家好,

今天早上有人告诉我,以下是leagal。


char * a =" Hello wrold";


内存自动分配。这是正确的吗?

解决方案

Win Sock写道:


嗨全部,

今天早上有人告诉我,以下是leagal。


char * a =" Hello wrold";

内存自动分配。它是否正确?



字符串的存储空间在翻译期间被搁置,并且

指针''a''设置为指向它''开始。


如果指针不是静态的,没有其他指针指向字符串,那么当''a''时,字符串变得无法恢复超出范围。


10月6日下午6:45,Win Sock< nos ... @ nospam.comwrote:
< blockquote class =post_quotes>
大家好,

今天早上有人告诉我,以下是leagal。


char * a =" ;你好wrold" ;;


内存会自动分配。它是否正确?



No.


字符串文字如Hello wrold就像你有一个const char的静态数组,并得到一个指向该数组的指针,转换为

char *而不是const char *。所以


char * a =" Hello wrold";




$ b完全相同$ b const char secret_array [] =" Hello wrold";

char * a =(char *)secret_array;


Win Sock写道:


大家好,

今天早上有人告诉我,以下是leagal。

char * a =" Hello wrold";


内存会自动分配。这是正确的吗?



不是在malloc()和朋友的意义上。 free(a)未定义。

常量字符串Hello wrold被放在内存中的某个地方作为一个名为

的匿名char数组,其地址放在一个。


拼写?法律和世界。


-

Joe Wright

所有事情都应该尽可能简单,但并不简单。

---阿尔伯特爱因斯坦---


Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?

解决方案

Win Sock wrote:

Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?

The storage for the string is set aside during translation and the
pointer ''a'' is set to point to it''s beginning.

If the pointer is not static and no other pointers point to the string,
then the string becomes irretrievable when ''a'' goes out of scope.


On Oct 6, 6:45 pm, Win Sock <nos...@nospam.comwrote:

Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?

No.

A string literal like "Hello wrold" works exactly as if you had a
static array of const char, and got a pointer to that array, cast to
char* instead of const char*. So

char *a = "Hello wrold";

works exactly the same as

const char secret_array [] = "Hello wrold";
char *a = (char *) secret_array;


Win Sock wrote:

Hi All,
somebody told me this morning that the following is leagal.

char *a = "Hello wrold";

The memory is automatically allocated on the fly. Is this correct?

Not in the sense of malloc() and friends. free(a) is Undefined. The
constant string "Hello wrold" is placed somewhere in memory as an
anonymous array of char, the address of which is placed in a.

Spelling? legal and world.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---


这篇关于为字符串分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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