C语言:值传递
来源:互联网 发布:手机回看电视软件 编辑:程序博客网 时间:2024/04/30 09:54
C语言函数传参是采用值传递的方式:
1-1int swap( int a, int b ){ int c = a; b = a; a = c;}int swapp( int *a, int *b ){ int c = *a; *a = *b; *b = c;}int main ( ){ int a = 5, b = 7; swap ( a, b ); printf( "%d %d\n", a, b ); swapp( &a, &b ); printf( "%d %d\n", a, b ); return 0;}输出:5 77 5
例如,交换函数swap和swapp的区别:都是值传递
swap函数传递的是,a和b值的拷贝,所以在main函数中的a和b的值没有交换。
swapp函数处置的是,a和b的地址拷贝,实际上交换a和b的地址。
如图所示
常见错误
- 传递指针时(1-2 ):foo传递是a的地址的拷贝,c的改变不会影响到a的指向。
- foo函数(1-3):如果在foo使用malloc或者calloc申请内存时,返回值是赋给c不是a,容易造成内存泄漏和访问越界。
- foo函数(1-4):使用realloc,扩展或者缩小内存空间时,如果出现nptr = realloc( ptr, size),ptr不等于nptr时,引起段错误和内存泄露.当pre等于npre时,不会发生错误。不易被发现的错误
1-2int w = 10;void foo( int *c ){ printf( "c:%p\n", c); c = &w; printf( "c:%p\n", c );}int main ( ){ int k = 0; int *a = &k; printf( "k:%p\n", &k ); printf( "a:%p\n", a ); foo( a ); printf("a:%p\n", a ); return 0;}输出k:0xbfafefd8a:0xbfafefd8c:0xbfafefd8c:0x804a020a:0xbfafefd8
1-3void foo( int *c, int m ){ c = malloc( m * sizeof( int ) );}修改void foo( int **c , int m ){ *c = malloc( m * sizeof( int ) );}int main( ){ int *w; foo( w, m ); 修改: foo( &w, m );}
1-4void foo( int *c, int m ){ c = realloc( c, m * sizeof( int ) );}修改void foo( int **c , int m ){ *c = realloc( *c, m * sizeof( int ) );}int main( ){ int *w; foo( w, m ); 修改: foo( &w, m );}
0 0
- C语言:值传递
- C语言 值传递与址传递
- C语言 值传递与址传递
- C语言地址传递与值传递
- C语言指针传递与值传递
- C语言函数传递与值传递
- C语言值传递与地址传递
- C语言值传递,C语言地址传递
- C语言值传递问题
- C语言的值传递
- C语言中的值传递
- c语言 值传递、地址传递、引用传递
- c语言值传递,地址传递,引用传递
- c语言值传递,地址传递,引用传递
- C语言值传递 地址传递 引用传递
- c语言值传递,地址传递,引用传递
- C语言的值传递、地址传递、引用传递
- C语言再学习 -- 值传递,址传递,引用传递
- Windows系统下如何安装Python以及对应pygame
- 求101-200之间的素数
- 学习计划
- 机器学习的本质是什么?
- BZOJ 1029 建筑抢修 贪心+堆
- C语言:值传递
- 杭电acm4515
- Mac 安装 Genymotion 下载虚拟机出现 The file is corrupt 提示问题解决办法
- 倒排索引详解
- 路径问题
- getParameter() getAttribute() setAttribute()
- C/C++ 之 _splitpath 获取文件路径
- android studio设置debug.keystore
- 杭电13952^x mod n = 1