Reputation:
I'm trying to separate my code more neatly by using functions. An issue I've been having is passing variables through different functions. If I leave all my code in my working function it will run no problem. It's when I create another function and pass variables to that function, that's when I get the issues.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void)
{
workings();
output();
}
void workings()
{
int x;
int i;
double 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 j = 0;
while (j < x) {
scanf("%d", &array[j]);
total += array[j] * array[j];
j++;
}
squareRoot = sqrt(total);
}
void output(int x, double overall, double squareRoot, int* array)
{
int k = 0;
while (k < x) {
overall = array[k] / squareRoot;
printf("%.3f ", overall);
k++;
}
}
Upvotes: 0
Views: 179
Reputation: 75062
You must pass arguments to functions which require them.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void workings(int *x_out, double *squareRoot_out, int** array_out);
void output(int x, double squareRoot, int* array);
int main(void)
{
int x;
double squareRoot;
int* array;
workings(&x, &squareRoot, &array);
output(x, squareRoot, array);
}
void workings(int *x_out, double *squareRoot_out, int** array_out)
{
int x;
double total = 0;
double squareRoot;
scanf("%d", &x);
int* array = malloc(x * sizeof(int));
if (!array) {
printf("There isn't enough memory \n");
return;
}
int j = 0;
while (j < x) {
scanf("%d", &array[j]);
total += array[j] * array[j];
j++;
}
squareRoot = sqrt(total);
/* pass data for later use to callee */
*x_out = x;
*squareRoot_out = squareRoot;
*array_out = array;
}
void output(int x, double squareRoot, int* array)
{
double overall;
int k = 0;
while (k < x) {
overall = array[k] / squareRoot;
printf("%.3f ", overall);
k++;
}
}
Changes I made are:
main()
(where the functions are used).workings()
in order to export data used in the function.overall
and i
in workings()
because they weren't used.overall
parameter from output()
function and declare it as local variable because the input is not used.main()
function to allocate memory for passing data and pass data between functions.Upvotes: 2