Click here to Skip to main content
14,577,799 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have to write a sphere () function that calculates the area and volume of a sphere. The function receives three transfer parameters: the radius and two pointers to double variables, in which the function sphere () writes back the area and the volume of the sphere . The input and output takes place in main (). 

For a sphere with radius R the following applies: area = 4 * PI * R * R, volume = 4 * PI * R * R * R / 3




What I have tried:

So far I've come to that, its literally not much but i dont know how to slove it
#include <stdio.h>
#define pi 3.14159
void sphere(double*, int*);

int main(void) {

    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);


  
    return 0;
}
void sphere() {
   
}
Posted
Updated 29-Jun-20 9:32am
Rate this:
Please Sign up or sign in to vote.

Solution 1

Unless otherwise specified, all function parameters in C are passed by value, not reference - which means that a copy of objects is passed to the function, and changes to that copy will not affect the outside world.
If you think about it, that makes a lot of sense.
What if it was passed by reference?
void foo(int bar)
   {
   bar = bar * 2;
   }
...
int x = 666;
foo(x);
would not cause any problems, and x would contain the new value.
But what happens if we do this?
void foo(int bar)
   {
   bar = bar * 2;
   }
...
foo(666);
Should the value of a constant be changed? That's not a good idea, not at all!

To tell C to pass by reference, you pass a pointer to the value:
void foo(int* bar)
   {
   *bar = *bar * 2;
   }
...
int x = 666;
foo(&x);
And the system will now not allow you to pass a constant, only a variable!

See here: Function call by reference in C - Tutorialspoint[^]
   
Comments
CPallini 30-Jun-20 2:09am
   
5.
Rate this:
Please Sign up or sign in to vote.

Solution 2

I have very little to add to Mr. Griff's solution. Just a few details :
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>       // defines PI and various mathematical things

void sphere( double radius, double * pVolume, double * pArea )
{
}


int main(void)
{
    double radius = 2.5;
    double volume = 0;
    double area = 0;
 
    sphere( radius, & volume, & area );

    // output values

    return 0;
}
   
Comments
Rick York 29-Jun-20 21:15pm
   
Note : math.h defines the constants with a leading M_ prefix. Pi is M_PI.
CPallini 30-Jun-20 2:09am
   
5.
KarstenK 30-Jun-20 3:18am
   
using the term objects is misleading.
Rick York 30-Jun-20 12:35pm
   
I think Grif did, I did not.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100