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

64 views Asked by At

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?

3

There are 3 answers

0
Tim Randall On BEST ANSWER

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);
}
0
David Schwartz On

You never assign ar or peri any values in main, so those variables don't every get assigned any values. That different variables with the same names get assigned elsewhere doesn't matter. (And the language would be pretty much unusable if it did.)

0
Daniel Kelsch On

You could do something like the below. The problem is caused by the fact that you never pass in ar or peri by reference. So you code does not change them.

Main

#include<stdio.h>
#include "circlehead.h"


int main()
{
  float r = 5.24;
  float ar = 0;
  float peri = 0;
    
    circle_Data(r, ar, peri);
    printf("Area is %f", ar);
    printf("Perimeter is %f", peri);

    return 0;
}

Header

#include <stdio.h>
void circle_Data(float r, float &ar, float &peri);
#define PI 3.14f

Body

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