I'm new in C. What is the difference between these:
a = b;
and
*a = *b;
(Assume both are integer pointers.)
I'm new in C. What is the difference between these:
a = b;
and
*a = *b;
(Assume both are integer pointers.)
Both are similar in that both statements assigns the value on the right-hand side to the left-hand side.
With
a = b;
you make a point to the same place where b is pointing. You now have two pointers to the same location.
For example, lets say we have the following setup:
int x = 10;
int y = 20;
int *a = &x; // Make a point to the variable x
int *b = &y; // Make b point to the variable y
Then if you do
a = b;
both a and b will be pointing to the variable y.
With
*a = *b;
(assuming both a and b are pointing somewhere valid) you assign the value of where b is pointing to where a is pointing.
If you understand arrays, it might be easier to see the last assignment as
a[0] = b[0];
It's doing exactly the same thing as *a = *b.
Taking the same example as above:
int x = 10;
int y = 20;
int *a = &x; // Make a point to the variable x
int *b = &y; // Make b point to the variable y
Then after
*a = *b;
the value of x and y will be the same, and it will be 20.
First let's assume the following declarations:
int x = 1;
int y = 2;
int *a = &x;
int *b = &y;
After this, all of the following are true:
a == &x // int * == int *
*a == x == 1 // int == int == int
b == &y // int * == int *
*b == y == 2 // int == int == int
After a = b, then the following are true:
a == &y
*a == y == 2
b == &y
*b == y == 2
We have assigned the value of b to a, so now a and b both point to y.
If instead you had written *a = *b, then we would have
a == &x
*a == x == 2
b == &y
*b == y == 2
Instead of pointing a to y, we have assigned the value of the object that b points to (y) into the object that a points to (x), so now both x and y have the value 2.
I would check the following guide out as it pretty much answers your question:
What are the differences between a pointer variable and a reference variable in C++?
Actually there are no difference in a=b and *a= *b.Both are same.Here a and b is point different element.
When you write the statement:
*a=*b
That means that the value of pointing element of b is assigned in a. And when you write this statement:
a=b
that means address of an element which is contain by b is now assigned in a. So those are same.
Here the code for better understanding:
#include<iostream>
using namespace std;
int main()
{
int x=10,y=20;
int *a,*b;
a=&x;
b=&y;
a=b;
cout<<*a<<" "<<*b<<endl;
a=&x;
b=&y;//for change the value of a and b we assign again
cout<<*a<<" "<<*b<<endl;
*a = *b;
cout<<*a<<" "<<*b<<endl;
}