It turns out you did not initialize the pointers. As the name itself indicates, they are pointers, so you have to point to some location in memory that is where the values are placed.
Soon when it does:
*area = PI * pow(R, 2.0);
You are saying, in the memory location where the area
pointer points, enter this value. But where is this? area
was not even assigned, so this results in undefined behavior and potentially segmentation fault .
The compiler itself helps you. Here's what I get when I compile your code:
||=== Build: Debug in Test (compiler: GNU GCC Compiler) ===|
... main.c|14|warning: 'area' is used uninitialized in this function [-Wuninitialized]|
... main.c|14|warning: 'volume' is used uninitialized in this function [-Wuninitialized]|
||=== Build finished: 0 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|
How do you fix it? Allocate space for the pointer, which would be the most normal:
float *area = malloc(sizeof(float));
float *volume = malloc(sizeof(float));
Now the pointers already point to a valid location in memory, even though they have no value assigned by you. This will already make the following assignments work correctly. Do not forget to include <stdlib.h>
to use malloc
.
Alternatively, you would create variables for area
and volume
as values and pass their addresses to the function:
float area, volume;
...
calc_esfera(raio, &area, &volume);
// ^------^-- aqui passa o endereço das variáveis no main
This last solution would even be preferable because it avoids allocation in heap , which causes more memory fragmentation and is slower. It also prevents you from having to worry about releasing memory with free
when you no longer need it.