char * pname =" Harry" [英] char* pname = "Harry"

查看:116
本文介绍了char * pname =" Harry"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下声明;


char * p;


p =(char *)malloc(20);


p =" harry" ; //< -------------它完全有效吗?


免费(p);

Statement given below;

char * p ;

p = (char*) malloc(20);

p = "harry" ; // <------------- Is it perfectly valid ?

free(p);

推荐答案

er****@gmail.com 写道:
下面的陈述;

char * p;

p =(char *)malloc(20);


你不必演员。
p =" harry" ; //< -------------它完全有效吗?

有效,但它没有做你所期望的,它改变p指向

string literal" harry"而不是malloc返回的内存。

free(p);
Statement given below;

char * p ;

p = (char*) malloc(20);
You don''t have to cast.
p = "harry" ; // <------------- Is it perfectly valid ?
Valid, but it doesn''t do what you expect, it changes p to point to the
string literal "harry" rather than the memory returned by malloc.
free(p);



糟糕,你试图释放哈利。


-

Ian Collins。


Bad, you are attempting to free "harry".

--
Ian Collins.



er **** @ gmail.com 写道:
以下声明;

char * p;

p =(char *)malloc(20);


失去演员阵容,除非你正在使用*非常旧的实现

(C89之前)。
p =harry ; //< -------------它完全有效吗?


完全有效,但不正确,考虑到上下文。而不是

复制字符串harry的内容。在

p指向的记忆中,你已经分配了字符串文字harry的地址。到p,

导致你忘记你刚分配的内存,这是一个内存泄漏的内存。


试试


strcpy(p,harry);


代替。别忘了#include< string.h>。

免费(p);
Statement given below;

char * p ;

p = (char*) malloc(20);
Lose the cast, unless you''re working with a *very* old implementation
(pre-C89).

p = "harry" ; // <------------- Is it perfectly valid ?
Perfectly valid, but not correct, given the context. Instead of
copying the contents of the string "harry" to the memory pointed to by
p, you''ve assigned the address of the string literal "harry" to p,
causing you to lose track of the memory you just allocated, which is a
memory leak.

Try

strcpy(p, "harry");

instead. Don''t forget to #include <string.h>.

free(p);




这将试图释放string literalharry,而不是你之前分配的内存





This will attempt to free the string literal "harry", not the memory
you allocated earlier.




John Bode写道:

John Bode wrote:
er****@gmail.com 写道:
下面的陈述;

char * p;

p =(char *)malloc(20);
Statement given below;

char * p ;

p = (char*) malloc(20);



失去演员,除非你正在使用*非常旧的实现
(在C89之前)。



Lose the cast, unless you''re working with a *very* old implementation
(pre-C89).



[snip]

或代码应该可以用于C和C ++。


/ Peter


[snip]
Or the code should be usable with both C and C++.

/Peter


这篇关于char * pname =&quot; Harry&quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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