通过指针传递 [英] pass by pointer

查看:71
本文介绍了通过指针传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include< stdio.h>

#include< alloc.h>


void func(int * p)

{

p = malloc(2);

* p = 10;

}


void main(void)

{

int * ptr = NULL;

func(ptr);

printf("%d",* ptr);

}


输出:0


为什么出是0,它应该是10?

任何机构可以解释一下吗?

#include<stdio.h>
#include<alloc.h>

void func(int *p)
{
p=malloc(2);
*p=10;
}

void main(void)
{
int *ptr=NULL;
func(ptr);
printf("%d",*ptr);
}

Output : 0

why out is comming 0, it should be 10?
can any body explain me?

推荐答案

ravi写道:
ravi wrote:

#include< stdio.h>

#include< alloc.h>


void func(int * p)

{
#include<stdio.h>
#include<alloc.h>

void func(int *p)
{



这里p有函数范围。

Here p has function scope.


p = malloc(2);

* p = 10;

}
p=malloc(2);
*p=10;
}



void func(int ** p)

{

* p = malloc(2);

** p = 10;

}

void func(int **p)
{
*p=malloc(2);
**p=10;
}


void m ain(void)
void main(void)



int main(void);

int main(void);


{

int * ptr = NULL;

func(ptr);
{
int *ptr=NULL;
func(ptr);



func(& ptr);


-

Ian Collins。

func(&ptr);

--
Ian Collins.


ravi写道:
ravi wrote:

#include< stdio.h>

#include< alloc.h>
#include<stdio.h>
#include<alloc.h>



alloc.h是非标准的。包括stdlib.h在其中获取

malloc'的原型。

alloc.h is non-standard. Include stdlib.h in it''s place to get
malloc''s prototype.


void func(int * p)< br $>
{

p = malloc(2);

* p = 10;

}


void main(void)
void func(int *p)
{
p=malloc(2);
*p=10;
}

void main(void)



使用int main(void)。

Use int main(void).


{

int * ptr = NULL;

func(ptr);

printf("%d",* ptr);

}


输出:0


为什么输出为0,应该是10?

任何机构可以解释一下吗?
{
int *ptr=NULL;
func(ptr);
printf("%d",*ptr);
}

Output : 0

why out is comming 0, it should be 10?
can any body explain me?



是的。 func获取ptr的新副本,本地称为p。你是
将你分配的内存的地址分配给这个局部变量,

*不是* ptr in main。当func结束时,p被破坏,你已经失去了追踪malloc''缓冲区的
。同时主要的ptr仍然设置为NULL。

你在printf中引用它,这是未定义的行为。


要解决这个问题,请通过*地址*的ptr到func。你可以这样做:

就像:

func(& ptr);

现在func将作用于ptr本身,而不是它的'本地副本。

Yes. func gets a new copy of ptr, which is locally called as p. You''re
assigning the address of your allocated memory to this local variable,
*not* ptr in main. When func ends p is destroyed and you''ve lost track
of the malloc''ed buffer. Meanwhile ptr in main is still set to NULL.
You''re deferencing it within printf, which is undefined behaviour.

To solve this problem pass the *address* of ptr to func. You can do
that like:
func(&ptr);
Now func will act on ptr itself, not it''s local copy.


ravi说:
ravi said:

void main(void)
void main(void)



在C中,main返回int。


-

Richard Heathfield

Usenet是一个奇怪的地方 - dmr 29/7/1999
http://www.cpax.org.uk

电子邮件:rjh在上述域名中, - www。

In C, main returns int.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.


这篇关于通过指针传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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