line 23 needs to call malloc() to allocate memory for the name then call strcpy() to copy the name. Hardcoding the number of filename pointers in your program is ok only if you know in advance the maximum you will need. But what happens to your program if there are 10 filenames in that directory? Or 100 filenames ? In those cases you will want to use a linked list of names.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>>filenames = (char *) malloc(sizeof *filenames);
That solves nothing. what is sizeof(*filenames) ?? Answer: number of bytes allocated to the array, not the number of bytes needed to copy d_name into the array. Here is what it should be: Note that you have to use the i counter because filenames is an array of pointers. And, in C language, you do not have to typecase the return value of malloc. Required in c++, but not in C.
filenames[ i ] = malloc(strlen(dir->d_name)+1);
strcpy(filenames[i],dir->d_name);
line 33: >> for (a = 2; a < i; a++){
why is that loop starting with 2 instead of 0.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>>When I tried this, I got two warnings:
>>1. assignment makes integer from pointer without cast
>>2. passing arg 1 of 'strcpy' makes pointer from integer without cast
Post code because what I posted is correct.
>>I have it starting at 2 because I only need the filenames, not the '.' and the '..'
Oh I see. You are correct. Normally we would not put them in the list.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
See line 11: you changed the declaration of filenames from an array of pointers to a simple pointer that is no longer an array. Change it back the way it was in your original post. You also have to change line 21 to use the array index.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343