I am implementing a program to divide all value in a
array by 100
then store them in b
array using malloc
. The problem is I got segmentation fault when printing value of b
in main
.
This is my code
#include <stdio.h>
#include <stdlib.h>
void divide(int *a, int n, double *b){
b=malloc(n*sizeof(double));
for(int i=0; i<n; i++){
b[i]=(double)a[i]/100.0;
}
//check: values still remain in b
for (size_t i = 0; i < 5; i++)
{
printf("%.2f ", b[i]);
}
}
int main(){
int a[]={1,2,3,4,5};
double *b;
divide(a,5,b);
//check: lost value and cause segmentation fault
for (size_t i = 0; i < 5; i++)
{
printf("%.2f ", b[i]);
}
free(b);
return 0;
}
So what cause this problem and how to fix it?
Thanks in advance.