关于值传递

来源:互联网 发布:淘宝平铺衣服修图技巧 编辑:程序博客网 时间:2024/06/05 19:44
首先来看这样的一个例子:

#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;
}

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

总结:1)指针变量也是变量;
   2)指针存取内容的特殊性。
原创粉丝点击