Home > Mobile >  Why are Pointers in Swap Function not Changing values in C?
Why are Pointers in Swap Function not Changing values in C?

Time:06-02

I'm trying to swap two floats using pointers ,

My code :

#include <stdio.h>

void swap(float* p, float* q);


int main() {
    double num1,num2;
    printf("Please write 2 numbers ");
    scanf("%lf %lf",&num1 , &num2);
    swap(&num1,&num2);
    printf("\nnum1 is  : %.2lf \n",num1);
    printf("num2 is  : %.2lf \n",num2);

    return 0;
}

void swap(float* p, float* q){
    float a;
    a=*p;
    *p=*q;
    *q=a;

}

My issues :

  1. The code doesn't swap
  2. The pointers in the swap function show value 0 for the pointer of the address I'm sending .

For example - input 99 22 -> gives me 0 :

Using Debugger I get

I don't get why I'm getting that , if according to this comment I have an address that I sent (let's assume I sent 00001 ) then a pointer to that address would be my value (99 in this example ) but I get 0 ...

I'd appreciate any help !

CodePudding user response:

As pointed out by comments, the problem is that your swap function takes float pointers while you are using double variables.

Since float type is used to describe floating point value over 4 bytes (32 bits) and the double type describes floating point value over 8 bytes (64 bits), when you pass double pointers to a function that treat them as float type, the values are wrongly assigned (over 4 bytes instead of 8 bytes) from one memory area to another.

The half of bits of a double does not make a valid corresponding float.

  • Related