I’m programming (and indeed close to completing) a CLI program to test the user on vocabulary, or indeed any set of questions and responses he/she would care to define.
Full source on github: https://github.com/megamasha/Vocab-Tester
Loading from a file and saving to a file are handled from separate functions, both outside of main(). At the moment they’re in the same source file, but I’d like to know how to do this both a) within the file, and b) in the case that they end up in a separate database ops file.
I want to allow the user to save to the file he most recently loaded, so I want my loaddatabase() function to define a global char * to the filename, which the savedatabase() function can then access.
If I declare a char * outside of any function, it is read-only and trying to write a filename to it causes a segfault.
If I declare it within the loaddatabase() function, savedatabase() can’t access it.
Will declaring the variable static allow other functions to access it, or if not, how can I allow two functions to access the same char *?
You can define a global variable by defining it in a single
.cfile:And by declaring it in a
.hfile:And by including the
.hfile in every file that uses the variable.The extern keyword declares the variable without defining it. It says the compiler that the variable exists in an other file.
So for your problem, you can define
char * databasein the file of your load/save functions, and declare it (extern char * database) in the file of your main function.You can do the same thing with
char database[1024]instead ofchar * databaseif you don’t want to bother allocating and freeing memory for the filename. This way you can directly write to database.