Hi Salem,
First of all, sorry for the late response.
Of course I'm using malloc (or xmalloc), but I have used it to allocate mem for the elements of the array, since I don't know how much memory is required for the array itself. This is because my function reads in names of image files from a dir, however the total number of these is unknown, so the final size of the
array cannot be calculated (or at least, I don't know how to do it...-.
Here is the code:
Code:
static char* str[1];
...
char **get_imagenames(const char *path, char* mask) {
bool masked = mask == NULL;
if(masked != 1) {
mask = replace_chr(mask,'*',NULL,CASE);
}
char* extension = (char *) path;
DIR *dir_ptr; int n = 0, m = 0, b = 0;
struct dirent *foo; str[m+1];
dir_ptr = opendir(path);
char* foo_ptr;
if(dir_ptr == NULL) {
printf("\nError: could not open dir '%s'!\n",path);
exit(EXIT_SUCCESS);
} else {
while((foo = readdir(dir_ptr)) != NULL) {
extension = (char *) &foo->d_name[find_chr_lastpos(
foo->d_name,'.')];
switch(masked) {
/* There are two possibilites.: If the file mask is defined (case1), then the func. will read in only those filenames whose extension is '*.mask'. Otherwise it makes an attempt to look up the extension in the array 'supported', in case of success the filename will be fetched, } else { -:) it'll be ignored. */
case 0:
if(strcasecmp(extension,mask) == 0) {
str[m] = (char *) xmalloc(foo->d_namlen + 1);
_snprintf(str[m],foo->d_namlen+1,"%s",foo->d_name);
b = 1; m = m++; } break;
case 1:
if(opendir(foo->d_name) == NULL && array_search(extension,
1,0,0,supported,NO_CASE) > 0) {
str[m] = (char *) xmalloc(foo->d_namlen + 1);
_snprintf(str[m],foo->d_namlen+1,"%s",foo->d_name);
b = 1; m = m++; } break; }
n = n++;
}
}
/* str is the array. Theoretically, now it contains 0 or more
elements, but if I try to count them with sizeof(str) / sizeof(str[0]), it says there is only 1 element and the size of str is 4. */
/* This part here is has no point at all. Qsort() needs the array size, but this will be always m, so size_t cc and char *bstr[m] are not required. I've declared them just to make some expirements with qsort. */
Code:
char *bstr[m];
if(str[0] != NULL) {
memmove(bstr,str,sizeof(str));
size_t cc = sizeof(bstr) / sizeof(bstr[0]);
qsort(str,cc,sizeof(str[0]),alpha_compare);
}
(void) closedir(dir_ptr);
if(b != 0) {
return str;
} else {
printf("\nError: '%s' dir doesn't conatin the required "
"type of img files or there are no image files at all.\n\n,path);
exit(EXIT_SUCCESS);
}
}
I can't figure out why the size of str[] is 4. Because I've declared as ... str[1]? But how do I know what size to specify here? Please advise.
Thanks in advance!
[code][/code]tagged by Salem