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
mallocand 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.That's my 2¢. It's possible that my error management code is somewhat perverse, but returning
-1on errors is more common that one would believe.