Reputation: 1904
I have a struct that has an array of strings (char **args). I need to be able to copy an array of strings (char *input[32]) into that element of the struct. For example:
Thing s;
s.args = input; //assuming input already has some strings in it
When I try to do that, the next time s.args = input is called, it completely overwrites the old input. How can I achieve this functionality in the appropriate manner?
EDIT
This is what the struct looks like.
typedef struct{
char **args;
} Thing;
Then in my function, I have declared:
char *args[512];
.....
args[count] = string //string is a char *
Then finally, I want to do:
s.args = input.
Upvotes: 0
Views: 12130
Reputation: 63481
You are not copying it. You are actually just setting the pointer. Effectively you have this:
char **args;
char *other[32];
args = other;
You need to actually copy the array - for that you need to allocate memory for it:
s.args = malloc( 32 * sizeof(char*) );
for( i = 0; i < 32; i++ ) s.args[i] = input[i];
That is a shallow copy - it will copy your string pointers but not duplicate them. If you change the contents of a string in input
, that change will be reflected in s.args
. To copy the strings, you must do this:
for( i = 0; i < 32; i++ ) s.args[i] = strdup(input[i]);
Since you have allocated memory, then before you overwrite s.args
again (and also when your program is finished) you need to free what you allocated. This includes the strings (if you called strdup
);
if( s.args != NULL ) {
// Only do the loop if you did a deep copy.
for( i = 0; i < 32; i++ ) free(s.args[i]);
// Free the array itself
free(s.args);
}
Upvotes: 5