Vishwas holla
Vishwas holla

Reputation: 17

why am i not able to initialize value of pointer to a variable in the below programme

#include<Stdio.h>

int main()
{
    int a ,b;
    int *p;
    int *q;
    printf("enter the value of a and b");
    scanf("%d%d",&a,&b);
    p = &a;
    q = &b;
    printf("value of a and b is %d and %d",a,b);
    a = *q;
    b = *p;
    printf("value of a and b is %d and %d",a,b);
}

i am not able to change value of b, even after redefining it to pointer p.

output

Upvotes: 0

Views: 59

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You are in fact assigning a value to b, but since you've changed the value of a, you will not notice the assignment, Let's say you enter 4 for a and 5 for b:

a = *q;  // q points at b, which is 5, so a = 5
b = *p;  // p points at a, which is now 5, so, b = 5

To swap the values, you could instead do:

int tmp = a; // store the value of a, 4
a = b;       // assign, a = 5
b = tmp;     // assign, b = 4 (the stored value)

or make a function out of it:

void swap(int *lhs, int *rhs) {
    int tmp = *lhs;
    *lhs = *rhs;
    *rhs = tmp;
}

and call it:

swap(&a, &b);

Upvotes: 3

Related Questions