本文介绍了通过动态分配参考了解传递的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试了解如何使用C语言通过引用传递参数。
因此,我编写了这段代码来测试参数传递的行为:
I'm trying understand how to pass a parameter by reference in C language.So I wrote this code to test the behavior of parameters passing:
#include <stdio.h>
#include <stdlib.h>
void alocar(int* n){
n = (int*) malloc( sizeof(int));
if( n == NULL )
exit(-1);
*n = 12;
printf("%d.\n", *n);
}
int main()
{
int* n;
alocar( n );
printf("%d.\n", *n);
return 0;
}
此处打印:
12.
0.
示例2:
#include <stdio.h>
#include <stdlib.h>
void alocar(int* n){
*n = 12;
printf("%d.\n", *n);
}
int main()
{
int* n;
n = (int*) malloc(sizeof(int));
if( n == NULL )
exit(-1);
alocar( n );
printf("%d.\n", *n);
return 0;
}
打印:
12.
12.
这两个程序有什么区别?
What's the difference of this two programs?
推荐答案
C是传递值,它不提供传递引用。
在您的情况下,指针(而不是它指向的对象)被复制到函数参数中(指针通过值传递-指针的值是地址)
C is pass-by-value, it doesn't provide pass-by-reference.In your case, the pointer (not what it points to) is copied to the function paramer (the pointer is passed by value - the value of a pointer is an address)
void alocar(int* n){
//n is just a local variable here.
n = (int*) malloc( sizeof(int));
//assigning to n just assigns to the local
//n variable, the caller is not affected.
您想要以下内容:
int *alocar(void){
int *n = malloc( sizeof(int));
if( n == NULL )
exit(-1);
*n = 12;
printf("%d.\n", *n);
return n;
}
int main()
{
int* n;
n = alocar();
printf("%d.\n", *n);
return 0;
}
或:
void alocar(int** n){
*n = malloc( sizeof(int));
if( *n == NULL )
exit(-1);
**n = 12;
printf("%d.\n", **n);
}
int main()
{
int* n;
alocar( &n );
printf("%d.\n", *n);
return 0;
}
这篇关于通过动态分配参考了解传递的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!