I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.
void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}
I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?
Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400开发者_如何学C, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.
For the 2089881670 problem, you should initialize your variable
like this :
double variable=0;
For the variable created somewhere and used far far away, you could use a global/static variable (sic), like this :
static double variable;
void function()
{
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}
I think sprintf needs &variable
as third variable. Try using sprintf( buf, "%lf", &variable);
Call your function with the address of the variable that will hold the value until you want to use it
void function(double *variable) {
/* ... */
*variable = 42;
}
and use the function like this
someotherfunction() {
double variable;
function(&variable);
/* ... lots of code ... */
/* ... and much later ... */
use(variable);
}
Or, make function
return the value rather than void
and saving it through a pointer
double function(void) {
return 42;
}
someotherfunction() {
double variable;
variable = function();
/* ... lots of code ... */
/* ... and much later ... */
use(variable);
}
You can use global variables for that, as @Cédric Julien suggested. The second problem should be resolved if you change your sprintf( buf, "%d", variable);
to sprintf(buf, "%d", (int)variable);
, because %d
parameter relates to integer types: http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
"I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?"
This is a pure program design problem, and has nothing to do with language syntax. If your user input is handled in main(), and then processed by some file that handles data processing, why would you need to "pass it between each and every function"? Pass it to the function that should handle it, end of story. You don't need no global variables.
精彩评论