I'm fairly new to c and I'm trying to understand and grasp malloc. My program takes an integer x input, then loops until x is met while also taking other integer inputs. I then do various calculations. However I'm getting a segmentation fault and I don't understand why.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void)
{
calculations();
}
void calculations()
{
int i;
int x;
int total = 0;
double squareRoot;
double overall;
scanf("%d", &x);
int* array = malloc(x * sizeof(int));
if (!array) {
printf("There isn't enough memory \n");
return;
}
int c = 0;
while (c < x) {
scanf("%d", &array[i]);
total = array[i] * array[i];
c++;
}
squareRoot = sqrt(total);
array = realloc(array, x * sizeof(int));
int b = 0;
while (b < x) {
overall = array[i] / squareRoot;
printf("%.3f ", overall);
b++;
}
}
array = realloc(array, x* sizeof(int));if you intended to extend - and then index - the memory allocation, it does not give any more memory, being the same allocation as the originalarray = malloc(x * sizeof(int));