关于值传递
来源:互联网 发布:淘宝平铺衣服修图技巧 编辑:程序博客网 时间:2024/06/05 19:44
很多人看到这段代码后,想着答案肯定是“hello world”。那么你错了,这段代码的运行结果是空的。为什么呢?我们来分析一下。#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也改变了。#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 <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;
}
- 关于函数值传递
- 关于java 值传递
- 关于值传递
- 关于值传递和址传递
- java关于值传递和引用传递
- 关于值传递和引用传递
- 关于值传递和引用传递
- 关于Python函数参数传递方式--值传递?引用传递!
- 关于值传递指针传递和引用传递
- 关于函数按值传递
- 关于值传递的若干问题
- 关于C#值类型,引用类型,值传递,引用传递
- 关于C#值类型,引用类型,值传递,引用传递
- C语言----关于值传递和地址传递
- 关于php按值传递和按引用传递问题
- 关于java中的值传递和地址传递
- 关于JAVA的值传递和引用传递&String
- 关于java方法参数是值传递还是地址传递。
- 学习语言
- hello
- DOCK
- WP 中各个事件
- 算法与编程
- 关于值传递
- Spring-boot入门
- C#多线程参数传递
- cocos2d-x-lua:API-sprite
- C#多线程学习(一) 多线程的相关概…
- 软件 项目管理 考试注意
- 利用DirectX实现声音播放
- MVVM
- IT 面试题