-
String Lifetime & Scope
Currently I am working to create a command line function that will alter data from an ini file.
The catch is to do this I will change the string in the startup array in the object defined. The code is restricted to not use C++ strings, but character arrays.
program <name>=<value>
My issue seems to be that if I want to do
program <name>=<value> <name>=<value> it will overwrite the data needed.
Code:
for( command line args)
{
char argument[256];
char *name;
char *value;
//tokenize argument into name and value
//insert into object
}
Now even if I was to put all those variables outside the loop the issue still comes up that another pair overwrites argument.
Is there a way to make sure each argument creates new memory without having to allocate it?
or is allocating memory the only way?
btw: I also have thought about changing name and value to their own char arrays but this shouldn't make a difference because I believe my problem has to do with scope and lifetime, not the variables I am using (unless Im completely wrong)
-
You could have an array of names and values.
Code:
//Up to five names
char *name[5];
char *value[5];
Or you could group name and value into a struct, and have an array of the struct.
Code:
struct Arguments
{
char *name;
char *value;
};
Arguments arg[5];
-
You must copy the string into each object. If your object contains a static length character array (like your argument variable above), you can just strcpy the values on insert. If your object contains a char* variable, then before calling strcpy you must allocate space for that object's copy of the string and deallocate that space when the object is destructed.
-
Well the object contains a ptr to the string, so thanks for all your help.
I think I'm going to use an array to easily limit the amount of pairs that can be changed and will have to worry a little bit less about the memory mgmt (thats the only part I still am not a fan of with C/C++ compared to other languages)
-
Of course, you should probably not complain about the memory management required by C++ since the language provides the C++ string class for that purpose. It is not the language's fault that you code is restricted to not use the tools provided. :p