나가을
나가을

Reputation: 37

i have a question about using pointer funtion

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
typedef struct {
    int a;
    int b;
}Point;
void Swappoint(Point*w, Point*m) {
    Point re;
    re=*w;
    *w = *m;
    *m = re;
}//@
int main(){
    Point m1 = { 1,2 };
    Point m2= { 3,4 };
    Swappoint(&m1,&m2);
    printf("%d %d %d %d", m1.a, m1.b, m2.a, m2.b);
    return 0;
}

at point @,this point i can't understand why pointer w can be re. re is not a pointer how can Point re can be pointer w?

Upvotes: 0

Views: 55

Answers (2)

Rohan Bari
Rohan Bari

Reputation: 7726

void Swappoint(Point *w, Point *m) {
    Point re;
    re=*w;    // Dereferencing 'w' and assigning the value containing it into 're'
    *w = *m;  // Value of 'm' after dereference, is assigned to 'w'
    *m = re;  // Value of 're' is assigned to 'm'
}

Dereferencing a pointer variable won't give pointer as the result, it'll give some value.

Upvotes: 0

natzelo
natzelo

Reputation: 66

This is what happens for each line inside Swappoint function:

Point re;

Create a static variiabe to hold point and call it re.

re=*w;

Go to the address of pointer w and copy the values of a and b to re

*w = *m;

Take the date of where m is pointing and place in where w is pointing

*m = re;

take the data to re and put that to where m is pointing

Here, pointer m is de-referenced

So while m is a pointer to Point , *m is Point itself

Upvotes: 1

Related Questions