关于值传递

首先来看这样的一个例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *p)
{
p=(char*)malloc(100);
strcpy(p,"hello world");
}
int main()
{
char *str=NULL;
getmemory(str);
printf("%s\n",str);
free(str);
return 0;
}

很多人看到这段代码后,想着答案肯定是“hello world”。那么你错了,这段代码的运行结果是空的。为什么呢?我们来分析一下。
首先将参数str=null放入内存,然后参数p=str=null,即p=null,接下来子函数就是对p的操作,完全和str没有关系,所以当输出str的时候还是空。那么如何解决这个问题呢?有两种方法:一种是用引用传递。即

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char *&p)
{
p=(char*)malloc(100);
strcpy(p,"hello world");
}
int main()
{
char *str=NULL;
getmemory(str);
printf("%s\n",str);
free(str);
return 0;
}

那么p和str公用一块内存,p的内容改变的同时,str也改变了。
另一种方法是使用双层指针,将str的地址传给指针p,那么p的内容发生改变的时候str也会改变。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getmemory(char **p)
{
*p=(char*)malloc(100);
strcpy(*p,"hello world");
}
int main()
{
char *str=NULL;
getmemory(&str);
printf("%s\n",str);
free(str);
return 0;
}

看完这么多,我们再来做一道题:

#include <string.h>
#include <stdio.h>
static const char *msg[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
char *get_a_day(int idx)
{
static char buf[20];
strcpy(buf, msg[idx]);
return buf;
}
int main(void)
{
printf("%s %s\n", get_a_day(0), get_a_day(1));
return 0;
}

想到结果了吗?
结果就是: Sunday Sunday

总结:1)指针变量也是变量;
   2)指针存取内容的特殊性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值