我有一个包含字符串数组(char **args)的结构。我需要能够将字符串数组 (char *input[32]) 复制到结构的该元素中。例如:
Thing s;
s.args = input; //assuming input already has some strings in it
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做时,下次调用 s.args = input 时,它会完全覆盖旧输入。如何以适当的方式实现此功能?
编辑
这就是结构的样子。
typedef struct{
char **args;
} Thing;
Run Code Online (Sandbox Code Playgroud)
然后在我的函数中,我声明:
char *args[512];
.....
args[count] = string //string is a char *
Run Code Online (Sandbox Code Playgroud)
最后,我想做:
s.args = input.
Run Code Online (Sandbox Code Playgroud)
你不是在复制它。您实际上只是设置指针。实际上你有这个:
char **args;
char *other[32];
args = other;
Run Code Online (Sandbox Code Playgroud)
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];
Run Code Online (Sandbox Code Playgroud)
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]);
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11812 次 |
| 最近记录: |