Assume I have char **argv, so that argv[0] = some string and argv[1] = another string etc…
I have another double pointer string array in a struct, call it s1->argv also defined as char **argv within the struct.
I am trying to copy argv into s1->argv1. I tried mallocing s1->argv to something with a max value (so 7 strings, each string of max 100 chars) and using strcpy but that obviously does not work. It only ends up copying argv[0]. This is how I used it: strcpy(*s1->argv, *argv)
How can I preserve each index of the array too?
The code below makes a copy of
argcandargvarguments ofmaininto user defined structure. The copy is exactly the same as original arguments (argvis terminated byNULLas in main). This code does not handle any abnormal events (like malloc failures, signal interruption etc.).You may want to avoid casting the result of
malloc(it is not required in C), there is a lot of debate whether this casting is a good or bad thing. The choice is yours. I value portability more, so I choose to cast, compile with all warnings enabled and eliminate all of them in the code (see the comments to this answer).Another option for copying the strings in
argvcould be usingstrdupfunction, then you could replace the three lines:with