【发布时间】:2014-06-20 08:00:27
【问题描述】:
J 在下面有一个代码,它显示给定目录中目录或文件的名称(这是 char[]/string)。我想将这些名称动态地放入数组中。在打印表 1 中显示正确的值(目录或文件的名称)是迭代的。但在其他打印 table3 中显示不正确的值。有人可以帮我吗?这是内存问题还是其他问题?
char** do_ls( char dirname[] ){
DIR *dir_ptr;
struct dirent *direntp;
char **strArray;
int count=0;
strArray = (char**)malloc(1 * sizeof(char*));
strArray[0] = NULL;
if ( ( dir_ptr = opendir( dirname ) ) == NULL )
fprintf(stderr,"ls1: cannot open %s\n", dirname);
else {
while ( ( direntp = readdir( dir_ptr ) ) != NULL ) {
if(strchr(direntp->d_name, '.') == NULL) {
strArray[count] = (char*)direntp->d_name;
printf("\nTable1: %s \n", strArray[count]);
count++;
strArray = (char **)realloc(strArray, sizeof(char *) * (count + 1));
printf("\nCount: %d \n", count);
}
}
strArray[count] = NULL; /* Terminate the array */
printf("\nTable3: %s \n", strArray[0]);
printf("\nTable3: %s \n", strArray[1]);
printf("\nTable3: %s \n", strArray[2]);
printf("\nTable4: %s \n", strArray[strlen(strArray)-1]);
printf("\nIndex: %d \n", strlen(strArray)-1);
closedir(dir_ptr);
}
return strArray;
}
【问题讨论】:
-
请提供一个完全可重现的示例,包括可编译的代码和显示问题的最少文件名集。
标签: c arrays memory-management dynamic-programming dir