My question is, I have an C project that has .c files:
trab.c
ordena.c
persistencia.c
persistencia.c
Is where I need to read X integer numbers from a .txt file
trab.c
has the main. Where I must call persistencia.c
to get an array of X (defined by a param in the main) integers and call sorting functions from ordena.c
passing said array as param.
My question is. What is the less comples way to do it? Can I declare a global array instead of passing someway through params? Can I use malloc to acess a var from another class?
Logan Rakai has a good answer, however, I wish to offer a different approach since my experience shows that it's better not to return dynamic allocated memory when possible (and sometimes it isn't).
A more flexible design would be to write a function that accepts a pointer and the array's size.
Also, when writing long term projects that need to be maintained (probably not just by yourself, but by other programs as well), it's good to keep "concerns" together.
A good example is that when the memory management (free
) is performed by the calling function, it is better if the memory allocation (malloc
) is performed in the same calling function... When splitting the memory management concern between different functions, it's more likely that future maintainers will introduce memory leaks into the code.
In this case, it's quite simple to allocate an Array using the stack or malloc
and pass it along.
i.e., here's a quick (somewhat useless) example for moving the memory management concern into the calling function (main
). Notice that this allows you to use both dynamic memory allocation and stack allocation when calling the array related functions.
size_t get_array_size(void /* or any parameters */) {
/* do whatever you need */
return 10; /*for our example */
}
void fill_array(int *arry, size_t size) {
while (size) {
size--;
arry[size] = 1; /* fill in data here */
}
}
int use_array(int *arry, size_t size) {
fprintf(stderr, "***\n");
while (size) {
size--;
arry[size] -= 1; /* do whatever */
fprintf(stderr, "array[%lu] == %d\n", size, arry[size]);
}
return 0; /* or return -1 for error */
}
int main(int argc, char const *argv[]) {
int array1[20];
int *array2;
size_t array2_size = get_array_size();
array2 = malloc(sizeof(*array2) * array2_size);
fill_array(array1, 20);
fill_array(array2, array2_size);
if (use_array(array1, 20))
perror("WTF?! "), exit(0);
if (use_array(array2, array2_size))
perror("WTF?! "), exit(0);
return 0;
}
That's my 2¢. It's possible that my error management code is somewhat perverse, but returning -1
on errors is more common that one would believe.