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?
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 ofarandperithat are local tomain()are modified bycircle_Data(), and the correct values can then be printed.Note that
circle_Data()gets a copy ofrthat it can modify, but that won't change the value ofrinmain(). It's a totally separate variable, just asarandperiwere in your first version.