how to fill char **array thats in a struct
typedef struct _stats_pointer_t
{
开发者_JS百科 char **fileNames;
stats_t stats;
} stats_pointer_t;
I need to fill 'fileNames'. Basically, I need to mimic this functionality:
char *fileNames[argc - 1];
fileNames[0] = argv[0];
... but using the struct stats_pointer. So I need to declare the struct, then probably allocate memory for the array but I'm not sure if that's necessary. Finally, I need to fill the array.
Revision: I need to declare the new struct as stats_pointer_t **sp;
because I need to pass this struct as an argument to a thread later. So I tried allocating memory for the struct and then for fileNames, but Eclipse's debugger tells me that it can't access fileNames when its being allocated. So how can I do this with stats_pointer_t **sp;
instead of stats_pointer_t sp;
stats_pointer_t p;
p.filenames = malloc(argc * sizeof *p.filenames);
for(int i = 0; i < argc - 1 ; i++) {
p.filenames[i] = malloc(strlen(argv[i+1]) + 1);
strcpy(p.filenames[i],argv[i+1]);
}
p.filenames[i] = NULL;
(And check for errors - like malloc returning NULL);
I would recommend you using a class instead of struct. So, in the class you should add a constructor and destructor for creating and deleting your array of strings
Something like this:
class MyClass
{
private char** array;
MyClass()
{
array = new char*[<the size of your array here>];
}
~MyClass()
{
//maybe free you string too here if it won't break some other code
delete [] array;
}
};
Also fileNames[0] = argv[0];
is not a good practice because it can lead to memory violation or mem leaks. You'd better use strcpy or strncpy if you are not absolutely sure what are you doing by using shared memory.
精彩评论