Addressing array elements that have been passed to a function

Status
Not open for further replies.

megadave

Ars Scholae Palatinae
1,042
Using C in Linux

Hi:


I'm trying to read a list of file names into an array of strings.
Yes...i know 'C' doesn't have strings, so its a 2 dimensional
array of characters.

The issue is that I pass the array (its a pointer after all)
to a function that lists the directory and copies the file names
into the array.

The problem is that i can't address the different array elements.
If I put the code in the main() function, it works fine, but
in the directory reading function, it doesn't let me address
the array elements using the subscript notation like array[4]

I get the error msg arithmetic on a pointer to an incomplete type

So my question is how do I address the array so that I can copy
the filenames in?


variable declarations

char path[100];
char names[100][100];

function call: readindir(path, names);



My function:


void readindir(char *path, char names[][]){

DIR *dir;
struct dirent *mydirent;
int i = 0;

dir = opendir(path);

while((mydirent = readdir(dir)) != NULL){
strcpy(names, mydirent->d_name);
printf("%3d : %s\n", i++, mydirent->d_name);
printf(" %s", names);
}
close(dir);
}
 
Code:
void readindir(char *path, char names[][])
You can't do that (the [][] part). That's why it complains that the type is incomplete. It can't increment/decrement the pointer because it doesn't know how big the subarrays are. I think this would be ok (haven't tested it though):
Code:
void readindir(char *path, char names[][100])
By telling the compiler that the subarrays are 100 char big, it now knows that the i-th subarray is at offset i*100.
 

stickboy

Ars Tribunus Angusticlavius
6,218
Subscriptor
In case you ever want to handle the dynamic case (which is a better idea, anyway... and I don't care how cheap RAM is these days, using ~10KB of memory for 100 (or 1) filenames seems wasteful to me), be sure to read the following answers from the comp.lang.C FAQ:


  • How can I dynamically allocate a multidimensional array?
  • My compiler complained when I passed a two-dimensional array to a function...
  • How do I write functions which accept two-dimensional arrays...

...
Heck, just read the whole section on pointers and arrays.

Edit:
By the way, that strcpy call looks dangerous. I hope you're 110% sure that strlen(mydirent->d_name) < 100 first. (Even if you are absolutely certain it will never overflow the buffer, it'd be a good idea to change it for maintainability.)
 
Status
Not open for further replies.