2

I am trying to make a swap function on my own with float pointers and it just does not work. For some reason I think I don't pass the float pointers to the function in the correct way.

#include <stdio.h>
#include <stdlib.h>

void swap(float *a, float *b);

int main() {
    float num1 = 0.0;
    float num2 = 0.0;

    float *px = NULL;
    float *py = NULL;

    printf("Please enter a decimal number: ");
    scanf("%f", &num1);
    getchar();

    printf("Please enter another decimal number: ");
    scanf("%f", &num2);

    px = &num1;
    py = &num2;

    printf("The numbers before swapping - \nNum1 = %f\nNum2 = %f\n", num1, num2);

    swap(&px, &py);

    printf("\nThe numbers after swapping - \nNum1 = %f\nNum2 = %f\n\n", num1, num2);

    system("PAUSE");
    return 0;
}

void swap(float *a, float *b) {
    float temp = *a;
    *a = *b;
    *b = temp;
}
2
  • 1
    Delete all occurrences of px and py in this code, passing &num1 and &num2 to your swap instead. Or lose the & in front of px and py in your swap call. If you didn't get at least a warning about float** not being compatible with float* in this, I'm shocked. Commented Mar 18, 2016 at 23:00
  • when compiling, always enable all the warnings, then fix those warnings. Using gcc -c -Wall -Wextra -Wconversion -std=gnu99 file.c -o file.o the compiler output: 1) line:4: passing argument 1 of 'swap' from incompatible pointer type 2) line 25: passing argument 2 of 'swap' from incompatible pointer type 3) line4 expected 'float*' but argument is of type 'float**'. Suggest fixing those problems before trying anything else. Note: do not ignore warnings. Commented Mar 19, 2016 at 18:23

2 Answers 2

2

You pass addresses of pointers to float instead of just addresses of float values. Remove the px and py variables and simplify your call to:

swap(&num1, &num2);

The compiler should have issued a warning about this type mismatch. Do not ignore these warnings, they indicate programming errors. Better even, enable more warnings: gcc -Wall -Wextra -Werror or clang -Weverything will produce more warnings about potential errors.

Sign up to request clarification or add additional context in comments.

Comments

0

Modify the prototype of swap to void swap(float** a, float** b );. Then modify the function's definition to:

void swap(float** a, float** b) {
    float temp = **a;
    **a = **b;
    **b = temp;
}

2 Comments

More indirection is obviously better. Make it three stars please.
I mistakenly thought about this as the problem of passing pointers as parameters in C, hence the more convoluted example. Thanks for your very lovely comment though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.