Today I've learned the utinization of pointer to deliver variables.Here's my code.
At first ,I made a mistake.
#include <stdio.h>
void change(int a,int b )
{
int temp=a;
a=b;
b=temp;
}
int main()
{
int a=3,b=4;
change(a,b);
printf("a=%d b=%d",a,b);
return 0;
}
Obviously,I've called the function change,but it still print a=3,b=4.
Why?
In fact ,parameters only deliver specific value,and the local variables only work in local part.So,in function,the value of a and b aren't changed.
The right code is following.
#include <stdio.h>
void change(int *a,int *b )
{
int temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int a=3,b=4;
change(&a,&b);
printf("%d %d",a,b);
return 0;
}
In this code,I use pointer.So in the function of change it has delivered the address of a and b.Then change(assign) value to the address of a and b.