tags:

views:

236

answers:

2
   typedef struct _stats_pointer_t
    {
     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;

Thanks, Hristo

A: 

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.

anthares
I'm not allowed to do that (this is the way the assignment is designed). I need to initialize this inside main.
Hristo
you should go for @leeeroy 's answer then
anthares
yes thank you for the strcpy advice.
Hristo
+1  A: 
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);

leeeroy
if I want to free this memory later on, I would have to loop through to free each pointer in the array as well as free p.filenames right?
Hristo
Need to declare `i` outside the loop.
Michael Myers
yes i have it declared outside of the loop. thanks.
Hristo
Yes, you will have to free each p.filenames[i] pointer first and then free p.filename. Declaring i inside the for statement is valid in C99.
leeeroy
@leeeroy: Declaring i inside the for loop is valid, but is it valid to then use it outside the loop?
Michael Myers