Turns out you didn’t initialize the pointers. As the name itself indicates, they are pointers, so have to point to some place in memory that is where the values are placed.
Just when it does:
*area = PI * pow(R, 2.0);
You’re saying, in the place of memory where the pointer area
point, put this value. But which location is this ? area
has not even been assigned, and therefore results in undefined and potentially Segmentation fault.
The compiler itself helps you in this regard. See 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 to fix ? Allocates space to 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 memory location, even if they have no value assigned by you. This will already make the following assignments work properly. Don’t forget to include <stdlib.h>
to use the malloc
.
Another alternative would be to create variables for the 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 the allocation in the 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.
I’m not sure if there is an error, maybe the console is closing when it closes the processing. If you add something like
scanf("%f", &raio);
after the lastprintf
, doesn’t solve??– rLinhares
I tested your code and it’s working: https://ideone.com/Nly6Qx only assigns a value to the variable
raio
for thescanf
does not work on this site– Ricardo Pontual
ueeee but that strange. Type, the console does not close. it only closes the program, without returning the result. I put up a system("pause"); to be sure.. it doesn’t really print here :s
– fernanda