Pointer Again


In some case, pointer seems is the only way to reach the goal. Especially, when we need to change the value by calling the funcion. If the variable in the function is a local variable, changeing it does not change the value of variable calling in. One efficient solution is use pointer variable in that funcion. When we change the value to which the pointer points, It means we change the value in the memory.
But keep in mind, even when we use pointer, we still can not just change the address varibale “ptr”, rather we should changed the “*ptr”.
For example.

#include

void swap(int *p1,int *p2);

main()
{
int x1=100,x2=200;

printf(“x1=%d,x2=%dn”,x1,x2);
swap(&x1,&x2);
printf(“x1=%d,x2=%dn”,x1,x2);
}

void swap(int *p1,int *p2)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
}
//The following code is wrong
void swap(int *p1,int *p2)
{
int *temp;
temp=p1;
p1=p2;
p2=temp;
}



Source link

Leave a Reply