I have multiple void functions that relies on the each individual output of the functions since there are multiple variables (that are the same throughout the code), where each functions' output will be "stored" to them and be passed to another.
So, I decided to make those variables into global variables by making them static .... right after all the necessary #include... codes.
I was able to utilize all functions (14 functions in total,all void) by only calling four of them (Each functions, after processing its own function, passes the result into another function and after series of passing, only four of them are needed to be called in int main())
Now, I created another void function that requires the global variables as its parameter since that void function relies on the data that all the other functions "copied and put" into the global variables declared earlier. (Which I found is not working, since I heard that storing data into global variables is not possible.)
Can anyone teach me if there is any other way to create series of functions which requires output of each individual functions?
I checked if the variables were stored properly, so I tried using printf method right after the #3 process. I found out nothing gets printed when I expected a value from the struct data to be printed.
Ex:
typedef struct database{
//... variables
}data;
typedef struct itembase{
//... variables
}item;
static data user1;
static data user2;
static data *pointer[10000];
static item *pointer2[10000];
static item current[10000]; //Shares same value of the bracket with *pointer2
static data sectionA[1][10000];
static data sub_section[3][10000];
static int datacounter = 0; //..will be put inside the bracket of *pointer
static int itemcounter = 0; //..will be put inside the bracket of *pointer2
static int typenum = 0; ..will be put inside the first bracket of all the sections and subsections
static int section_count = 0; //..will be put inside the second bracket of all sections
static int sub_section_count[3] = {0}; //..will be put inside the second bracket of all sub_sections. The [3] will be the value of the typenum.
void load_data() // Accepts User's input and store them into struct data's variable using singly-linked list
{
//.... All data will be stored to *pointer[datacounter]
binarycheck(pointer[datacounter]->encoding,*pointer,datacounter);
//.... The `typedef struct` of data contains 12 variables. After storing 12 variables, datacounter will be ++ and the program will still continue to accept input from the user
}
void load_item()
{
//.... All item will be stored to *pointer2[itemcounter]
memcpy(¤t[itemcounter],pointer2[itemcounter],sizeof(item));
}
void binarycheck(data encoding,data *pointer,int datacounter)
{
if ((encoding&128)==128){
typenum = 3;
memcpy(§ionA[typenum][section_count],pointer,sizeof(data));
sub_sectionA[typenum][sub_section_count[typenum]] = sectionA[typenum[section_count];
section_count++;
sub_section_count++;
}
}
void askitem(data user)
{
// Tried putting `printf(" %s User1 Data#1",user1.firstdata);` and it works perfectly fine.
// Ask for user's selection on item
// If the item is found, then the content of that item will modify the data of the variable of `user`
}
void askinput(data user)
{
int whattype = 0;
int whatsub = 0;
printf("What type do you want?: \n);
scanf("%d",&whattype);
if (whattype == 1)
{typenum = 1;}
printf("What Sub type do you want?: \n);
scanf("%d",&whatsub);
if (whatsub == 1)
{ user = sub_sectionA[typenum][sub_section_count[typenum]];}
askitem(user);
}
void final_print(data user, data user2)
{
printf("%d\n",user.Adata);
printf("%d\n",user2.Adata);
}
int main()
{
load_data();
load_item();
askinput(user1);
//Tried putting `printf(" %s User1 Data#1",user1.firstdata);` but nothing shows.
askinput(user2);
//Nothing shows
final_print(user1,user2); //Nothing shows
}
Take a look at this function:
void askinput(data user)
Here you pass user by value to the function. When you pass by value, the function receives a copy of the variable. Changes that you make inside the body of that function only affect the copy. They are not visible to the caller's variable.
Instead you need to pass a reference. In C that means passing a pointer to a variable:
void askinput(data *user)
Inside the body of the function you need to de-reference the pointer to access members. So you use -> rather than . to refer to members.
And when you call the function you need to pass a pointer to the variable. So the call becomes:
askinput(&user1);
Frankly I do not understand why you are using global variables here at all. It's generally preferable to pass parameters otherwise you do find yourself struggling to keep track of which different version of the variable you are meant to be working on.
Finally, you have written your entire program and trying to debug this specific problem in the context of the entire program is confusing you. You really should have cut this down to a 10 or 20 line simple reproduction. Being able to do that in the future will make life much easier for you.
Related
Just out of curiosity, I'm trying to understand how pointers to functions work in C.
In order to associate a function to a typedef, I've declared a pointer in it, and then I've stored the address of the desired function in there.
This is what I was able to achieve:
typedef struct
{
void (*get)(char*, int);
char string[10];
} password;
int main()
{
password userPassword;
userPassword.get = &hiddenStringInput;
userPassword.get(userPassword.string, 10);
return EXIT_SUCCESS;
}
While this does actually work perfectly, I'd like for "userPassword.get" to be a shortcut that when used calls the hiddenStringInput function and fills in the requested arguments (in this case, an array of characters and a integer).
Basically, since I'm always going to use userPassword.get in association with the arguments "userPassword.string" and "10", I'm trying to figure out a way to somehow store those parameters in the pointer that points to the hiddenString function. Is it even possible?
The way I see this usually done is by providing a "dispatch" function:
void get(password * pw) {
pw->get(pw->string, 10);
}
Then, after setting userPassword.get to your function, you call just:
get(userPassword);
Obviously this adds some boilerplate code when done for multiple functions. Allows to implement further funny "class like" things, though.
You can do this in Clang using the "Blocks" language extension. As commented, there have been attempts to standardize this (and it's not been received with hostility or anything), but they're moving slowly.
Translated to use Blocks, your example could look like this:
#include <stdlib.h>
#include <Block.h>
typedef void (^GetPw)(int); // notice how Block pointer types are used
typedef void (*GetPw_Impl)(char*, int); // the same way as function pointer types
typedef struct
{
GetPw get;
char string[10];
} password;
extern void hiddenStringInput(char*, int);
extern void setPw(char dst [static 10], char * src);
GetPw bindPw (GetPw_Impl get_impl, char * pw)
{
return Block_copy (^ (int key) {
get_impl (pw, key);
});
}
int main()
{
password userPassword;
setPw(userPassword.string, "secret");
userPassword.get = bindPw(hiddenStringInput, userPassword.string);
userPassword.get(10);
return EXIT_SUCCESS;
}
There are some subtleties to the way arrays are captured that might confuse this case; the example captures the password by normal pointer and assumes userPassword is responsible for ownership of it, separately from the block.
Since a block captures values, it needs to provide and release dynamic storage for the copies of the captured values that will be created when the block itself is copied out of the scope where it was created; this is done with the Block_copy and Block_release functions.
Block types (syntactically function pointers, but using ^ instead of *) are just pointers - there's no way to access the underlying block entity, just like basic C functions.
This is the Clang API - standardization would change this slightly, and will probably reduce the requirement for dynamic memory allocation to copy a block around (but the Clang API reflects how these are currently most commonly used).
So, I've just realized that I can write functions directly inside of structs
typedef struct
{
char string[10];
void get(void)
{
hiddenStringInput(string, 10);
return;
}
void set(const char* newPassword)
{
strcpy(string, newPassword);
return;
}
void show(void)
{
printf("%s", string);
return;
}
} password;
Now I can just call userPassword.get(), userPassword.show() and userPassword.set("something"), and what happens is exactly what the label says. Are there any reasons I shouldn't do this? This looks like it could come pretty handy.
EDIT: So this is only possible in C++. I didn't realize I'm using a C++ compiler and by attempting to do random stuff I came up with this solution. So this isn't really what I was looking for.
I have my own implementation of C hash_map_t struct that I can use as below?
// string value allocator
allocator_t *str_value_allocator;
allocator_init(&str_value_allocator, string_allocate_handler, string_deallocate_handler);
str_hash_map_init(&str_hash_map, str_value_allocator, 5);
str_hash_map_put(str_hash_map, test_key, test_val, strlen(test_val));
str_hash_map_get(str_hash_map, test_key, NULL)
str_hash_map_remove(str_hash_map, test_key)
str_hash_map_free(str_hash_map);
I would like to use this hash map in function like below:
void handle_keyboard_input(char **tokens, size_t num_tokens) {
char *virtual_key_name = strtok(tokens[1], " ");
size_t num_flags = 0;
char **modifier_flags = str_split(tokens[2], ", ", &num_flags);
// map virtual_key_name (char *) to virtual_key code (int)
// foreach modifier flag (char *) map to modifier flag code (int)
}
I can create 2 hash_maps for key_name -> key_code mapping and flag_name -> flag_code mapping. The problem is that I don't want to create this flag each time the request handler function is called but have only one data structure instance from first call of the function and in successive function invocations I want to reuse this data structure (data store) already created.
My hash_map is created on the heap so there isn't possibility to allocate it like the array somewhere inside library source code file.
In Java or even C++ I could create some Singleton pattern or static member but such concept is not available in C language. Probably I could create this hash_map at program startup somewhere at the beginning of program but how could I pass reference to library used by the program.
My recent idea was to use static hash_map_t variable inside my handle_keyboard_input function and somehow initialised it only when it is NULL (the first function call), and if variable isn't NULL in successive calls just reuse previously initialised hash_map_t structure.
What will be the best approach to this problem?
UPDATE
Could I use such code?
static str_hash_map_t *virtual_keys_map = NULL;
static str_hash_map_t *modifier_flags_map = NULL;
if (virtual_keys_map == NULL) {
virtual_keys_map_init(&virtual_keys_map);
}
if (modifier_flags_map == NULL) {
modifier_flags_map_init(&modifier_flags_map);
}
Since this appears to be a library, you have several options:
You can make your library more "object oriented" and force the user to do the proper instantiation. For example, you would have your ADT struct defined as KeyboardHandler, and then your handle_keyboard_input would look something like this instead:
void KH_handle_input(KeyboardHandler self, char **tokens, size_t num_tokens);
Which means the caller is now responsible for doing the instantiation of that single part:
// caller must get the ADT instance at some point, and you don't care when
KeyboardHandler kh = KH_init();
KH_handle_input(kh, some_tokens, num_tokens);
// some other part can be initialized later
MouseHandler mh = MH_init();
MH_handle_input(mh, some_tokens, num_tokens);
It's possible to create a library initializer for both Windows and POSIX dlls. So you can let this be done automatically instead.
Otherwise, it seems like you will have to make this "check" anytime your functions want to use this potentially-uninitialized hash tables (perhaps it's a single function, but anyway). In which case, I would at least refactor it into a separate function:
void handle_keyboard_input(char **tokens, size_t num_tokens) {
initialize_hashes_if_needed();
// ...and then the rest of the function
}
The reasoning is that you don't want to have to modify several functions if you decide there is something else that needs to be malloced.
Yes, code above cause that pointers will be initialised just once (or if you set them to NULL, condition will be true and it will init again) and stay in memory even if you get outside of function.
The lifetime of function static variables begins the first time the program flow encounters the declaration and it ends at program termination - in other words they are global variables.
Also the name of this variable is only accessible within the function, and has no linkage.
Still need to take great care if you think you need a globally-accessible variable. Read here.
static str_hash_map_t *virtual_keys_map = NULL;
static str_hash_map_t *modifier_flags_map = NULL;
if(virtual_keys_map == NULL) {
virtual_keys_map_init(&virtual_keys_map);
}
if(modifier_flags_map == NULL) {
modifier_flags_map_init(&modifier_flags_map);
}
I picked up the bad habit of Global Variables early on, So ive been trying to distance myself by using local variables and learning call by reference/value which isn't so bad until I run into a problem like this, say I have a function Menu() which contains a main menu, and an array, then from the Menu I'd go to a function and do stuff with the Array, now I usually get stuck here my functions are usually of void type, but usually for my programs I use a if selection to get back to the Menu, like If(userinput ==2){Menu();} usually this causes two problems 1. When I enter Menu it resets all the variable values
2.If i have this function in multiple places it will start giving me parameter errors.
These problems discourage me and make me lean towards the side of Global Variables.
Example:
menu(){
int array[100];
functionadd(array);
}
functionadd(array[])
{
int userinput;
do{
//lets the just say here the program does things to my array.
// usually when I want to go back to the menu I'd do something like this
printf("Again or back to menu?1(Again) or 2(Menu)")
scanf_s("%d%[^\n]", &userinput); '\n'==getchar();
} while(userinput == 1)
if(userinput != 2){Menu();} /*this would bring me back to
the menu but my array would be back to as its original state
when it was called in Menu I understand why this happens I
just need to learn how to counter act it*/
}
Some pseudo code to not have a variable to be "reset" with static keyword:
int Menu(){
static int remember = 0;
remember++;
return remember;
}
int main(){
printf("remember = %d\n", Menu());
printf("remember = %d\n", Menu());
printf("remember = %d", Menu());
}
output:
remember = 1
remember = 2
remember = 3
Notice that a global variable is, like Ron says, is a variable for the lifetime of the program. So is a static variable, but in this case it isn't accessible in another function. Also, a static variable isn't really thread safe
"All non-local state must be accessed through atomic operations and
the data-structures must also be reentrant."
Well, You're calling is something like this:
main()
{
menu();
}
menu()
{
yourfunction();
}
yourfunction()
{
if(userinput==2)
menu();
}
Here, you can observe that you're again calling menu() but not returning back..
If you're at the depth in menu(), if you'll exit, will return to yourfunction() but not the main().
I'll recommend you to use codes similar to the following:
menu()
{
do
{
yourfunction();//call your function
//after the completion ask to continue
printf("Do you want to continue? (Y/N) ");
fflush(stdin);
scanf(" %c",&choice);
}while(choice=='y'||choice=='Y');
}
void yourfunction()
{
//do only functional job
}
This will help you to return to the menu() and ask you for the continuation.
And also the values will remain as you want them to.
Edit:
Or if you want to stick to your habit of programming.
Simply tell the program what to do when user input is 1 (i.e. not equal to 2)
And don't define anything when 2 is input.
It will automatically return to menu()
menu()
{
yourfunction();
}
Yourfunction()
{
if(userinput==1)
{
// do this
}
}
Or other way:
menu()
{
yourfunction();
}
Yourfuntion()
{
if(userinput!=2)
{
//do this
}
}
If the function gets userinput as 2 it will get back to menu().
Over.. :-)
If you save a variable like static you'll not lose the data the function had before, cause the variable won't be destroyed at the end if the function and the stack won't be cleaned. Example:
static int var=0;
var++;
return var;
If you call the function 10 times the variable will be increased ten times.
You should take note of the following:
In C, all parameters are passed using call by value.
When you passing an array as parameter to a function, it decays as a pointer to the first element of the array.
Call by value doesn't mean you can't modify some function's local variable from another function. For that, you pass a pointer as parameter and then from the callee function assign value to its dereferenced stated.
eg:
void f(int *c)
{
*c = 7;
}
int main(void)
{
int count = 4;
f(&count);
printf("%d", count);
return 0;
}
The reason people discourage overuse of global variables is because those variables will be taking memory for the life of the program (process really).
But, in this specific case, that's the behavior you want. You want to remember the state of the menu between calls, and you can either implement a structure yourself and save the state in the calling function, or you can simply declare the variable globally.
What irks people is when every variable is global, regardless of whether they need to be. In a language like C, which basically only survives because of its ability to manually manage memory to the utmost efficiency, it hurts our brains to see people wasting it. In general, it's a code smell to see any global variables that aren't constants. As a commenter has pointed out, there are other reasons to avoid using globals. Rather than iterate through them all, I'll leave this here: why globals are bad
Note, I'm not trying to be mean, just not sure which of those pages is the best resource, so I gave OP all of them.
Edit: a few other points. You also could easily accomplish what you need by either passing a pointer containing the value you may or may not edit within the function as a parameter, but the solution I would probably implement given what you've said is like this:
int choice = menu();
case (choice ):
//logic here
Hi I am working on a project where I access info from a file and then put it into an array of objects then manipulate the data in the object from a options from a menu. The problem I am currently having is that one of the options in the menu is to add a new element to the object. The project states that I must use an array of objects so I can't just use a vector the class that I'm putting the array into to resize it uses a temporary dynamic array for the object then deleting the original array.
Here's what the class looks like
class Info
{
private:
string name;
double money;
public:
Info(){
name="";
money=0;
}
void Setname(string n){
name=n;
}
void Setmoney(double m){
money=m;
}
string GetName()const{
return name;
}
double GetMoney()const{
return money;
}
};
now that was just a sample of the class the actual class has equations with it to alter the money variable but for the purpose of this question this is all that is needed. Now here is the function where I am having the problem
void Addinfo(Info in [], int & size){
string newname;
double newmoney;
cout<<"What name are you going to use?"<<endl;
cin>>newname;
cout<<"Now How much money do you have currently"<<endl;
cin>>newmoney;
Info *temp= new Info[size+1];
for(int index=0; index<size;index++){
temp[index].Setname(in[index].GetName());
temp[index].Setmoney(in[index].GetMoney());
}
delete []in;
temp[size].Setname(newname);
temp[size].Setmoney(newmoney);
in=temp;
size=size+1;
}
Now when I run the program everything runs fine until I try using this function in which the data in the arrays gets corrupts. Am I supposed to make the in Info variable a new dynamic array that can hold the can hold all the info then use another for loop to put the variables into the new dynamic array or I am supposed to do something else. Also remember that I must use arrays for this. Also when deleting a dynamic array am I supposed to make the former array equal to zero after deleting or is that something else?
When you have a function with a type valueName[] array parameter then you just pass the address of that array parameter to the function. The calling function has the ownership of that array. Besides the function signature you always have to consider a contract between the caller and the called function that defines the ownership of the data passed by pointer.
Your function AddInfo gets an array passed by pointer and the calling function expects that the data is available after the function call. So the function violates the contract when you delete []in.
Your function uses a parameter in as (local) variable when you assign a new value with in=temp;. That's legal. But you can't expect that the changed local variable has any effect to the caller. With the current function signature is possible to call the function in this way:
Info infos[5];
Addinfo(&info[3], 2);
Obviously it makes no sense to modify &info[3]. When your contract shall allow adding some data to the array you need a signature that allows changing a pointer. One example would be:
void Addinfo(Info*& in, int& size, string newname, double newmoney)
{
Info *temp= new Info[size+1];
for(int index=0; index<size;index++){
temp[index].Setname(in[index].GetName());
temp[index].Setmoney(in[index].GetMoney());
}
temp[size].Setname(newname);
temp[size].Setmoney(newmoney);
delete []in;
in = temp;
size=size+1;
}
void Addinfo(Info*& in, int& size)
{
string newname;
double newmoney;
// input data
cout<<"What name are you going to use?"<<endl;
cin>>newname;
cout<<"Now How much money do you have currently"<<endl;
cin>>newmoney;
// TODO: data validation.
// add data to array
Addinfo(in, size, newname, newmoney);
}
I have factored out the change of the array from the input. This allows a more simple testing of that function.
Is there a way to reset variables declared as static within a function? The goal is to make sure that the function is not called with lingering values from an unrelated call. For example, I have a function opearting on columns of a matrix.
int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows
if (column != whichColumn){
memset(v,0,size);
whichColumn = which;
}
//do other things
}
The function is called n times, once for each column. Is this a proper way of "re-setting" the static variable? Are there other general fool-proof ways of resetting static variables? For example, I want to make sure that if the call is made with a new matrix with possibly different dimensions then the vector v is resized and zeroed etc. It seems the easiest way may be to call the function with a NULL pointer:
int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows
if (A == NULL){
FREE(v);
whichColumn = 0;
}
//do other things
}
Use an idempotent initializer function and global variables instead.
For example:
int foo;
int *m = NULL;
static void InitVars() {
foo = 0;
if (m != NULL) {
free(m);
}
m = malloc(sizeof(int)*5);
memset(m, 0, sizeof(int)*5);
}
If your initializer is really idempotent, you can call it again to reset the variables.
If you need this to be called automagically, use __attribute__((constructor)) (for GCC) like so:
static void InitVars __attribute__((constructor)) ();
However, you should note that if you need to do this, you should reconsider using in-function static variables and instead use passed-in fresh ones that are returned/written and passed to subsequent related calls.
I'd recommend turning it into a struct and writing a small helper function for managing the semantics of what you're trying to do. It could return the buffer if the request is appropriate for its size, or create a new one on demand (and free the old one) if necessary.
One approach I've seen used when a C module was imported to C++ was to surround the whole module with a class wrapper, and replace all static variables inside functions with uniquely-named "global" varaibles outside the functions. I don't know any good way to achieve a similar effect for projects involving multiple source files, though I'd like to know if one exists. I have some embedded system code in C, which I simulate by adding some C++ wrappers in VS2005. For example, I have I/O registers defined so that something like TX1CON = 0x5C; would translate into something like IOMAP(0x251).P = 0x5C; IOMAP is a property which would send "write 0x5C to address 0x251" to a hardware-simulation program. This approach works well, but I can't do a clean reset. Any ideas?
An approach which can sometimes be helpful if one needs a "reset" method which can hit an unknown number of functions or modules is to have a global counter for how many times that reset method has been called, and then have each function or module include code like:
extern unsigned long global_reset_count;
void do_something(int whatever)
{
static ... this, that, the other, etc. ...;
static unsigned long my_reset_count;
if (my_reset_count != global_reset_count)
{
my_reset_count = global_reset_count;
... initialize this, that, the other, etc ...
}
}
In some multi-threading contexts, if the initialization of the static variables may depend upon some global variables, one may wish to replace the "if" with a "while"; in such a case; memory barriers may also be needed in such a case, though the exact requirements would vary depending upon the operating environment.
Also, an alternative pattern that may be useful within embedded systems would be to have a modules_initialized global variable which gets set to 0 by the global reset method, and then have each module start with something like:
if (!atomic_bit_test_and_set32(&modules_initialized, FOOBOZZ_MODULE_ID))
{
... Initialize module FOOBOZZ ...
}
This would require that there be no more than 32 module ID's, and would require that they be uniquely allocated somehow, but some systems can handle that pretty nicely. For example, a linker may allow one to define a "data section" from address 0-31 of an address space independent from any other; if each module declares a single-byte variable within that address space, the linker could generate the appropriate addresses for those variables.
you could build your function in such a way that if you call it with zero parameters, then it will reset its internal static variables
here is an example :
int foo(matrix *A = NULL, int colnum = 0, int rownum = 0)
{
static int whichColumn;
static int *v; //vector of length A->nrows
if (A == NULL){
FREE(v);
whichColumn = 0;
}
//do other things
}
You actually just have to call function to reset like this:
foo(); // internal values would then be reset
Make sure that all your parameters to the function has default values, if for example you pass an optional, then make sure it has = boost::none as default value