Creating a global char pointer
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 .c
file:
char * database;
And by declaring it in a .h
file:
extern char * database;
And by including the .h
file 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 * database
in 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 of char * database
if you don't want to bother allocating and freeing memory for the filename. This way you can directly write to database.
You need to declare a character array, i.e. char filename[260].
精彩评论