Search code examples
cfunctionpointerserror-handlingpass-by-pointer

Why am I not getting the desired output for this program using pointers in functions in c?


Header file: circlehead.h

#include <stdio.h>
void circle_Data(float *r);
#define PI 3.14f

C FILE1: circle.c

#include "circlehead.h"
void circle_Data(float *r)
{
    float ar=0,peri=0;
    ar= PI * (*r) * (*r);
    peri=2 * PI * (*r);
}

MAIN FUNCTION circle_main.c

#include<stdio.h>
#include "circlehead.h"
int main()
{
    float r=5.24;
float  ar, peri;
    
    circle_Data(&r);
    printf("Area is %f", ar);
    printf("Perimeter is %f", peri);
}


I have linked the files into a single executable:

gcc -c circle.c
gcc -c circle_main.c
gcc -o x_exe circle.o circle_main.o 
./x_exe

But I am getting the output as area: 3.728 and perimeter: 0.000 The code was compiled successfully. What am I doing wrong?


Solution

  • You had the right idea (passing a pointer) but you used it in the wrong way.

    The problem was that you passed a pointer to the variable that wouldn't be changed, and didn't pass pointers to the variables that you did need to be changed, by circle_Data(). This version ought to behave in the way you wanted. The values of ar and peri that are local to main() are modified by circle_Data(), and the correct values can then be printed.

    Note that circle_Data() gets a copy of r that it can modify, but that won't change the value of r in main(). It's a totally separate variable, just as ar and peri were in your first version.

    #include "circlehead.h"
    void circle_Data(float r, float* ar, float* peri )
    {
        *ar= PI * r * r;
        *peri=2 * PI * r;
    }
    
    
    #include<stdio.h>
    #include "circlehead.h"
    int main()
    {
        float r=5.24;
        float ar, peri;
        
        circle_Data(r, &ar, &peri);
        printf("Area is %f", ar);
        printf("Perimeter is %f", peri);
    }