Originally Posted by
usernamer
e.g. if the user enters 5 and 7, then I need to create an array[7] in the function, do stuff to it, and then be able to use it in main again.
As Adak mentioned, using malloc is called for here. Keep in mind that each function that manipulates your array must have some way to know its length. The two basic approaches are to end the array using a special marker of some kind (the approach used by strcpy, for example), or to pass the length of the array along with the array itself. Here is an example of the second approach:
Code:
#include <stdio.h>
#include <stdlib.h>
// create array with length arrlen
void arrcreate(double **arr, int arrlen);
// set all elements to x
void arrsetall(double *arr, int arrlen, double x);
// release memory
void arrdestroy(double **arr);
int main()
{
double *a = NULL;
arrcreate(&a, 10000);
arrsetall(a, 10000, 1.234);
arrdestroy(&a);
exit(EXIT_SUCCESS);
}
void arrcreate(double **arr, int arrlen)
{
if (*arr != NULL) {
printf("arrcreate: argument 1 must be a NULL pointer\n");
exit(EXIT_FAILURE);
}
*arr = malloc(arrlen * sizeof(**arr));
if (*arr == NULL) {
printf("arrcreate: allocation error\n");
exit(EXIT_FAILURE);
}
}
void arrsetall(double *arr, int arrlen, double x)
{
for (int i=0; i < arrlen; i++)
arr[i] = x;
}
void arrdestroy(double **arr)
{
free(*arr);
*arr = NULL;
}