[英]C, looping array of char* (strings) does't work. Why?
I have problem with my array of char*- 我的char *数组有问题 -
char *original_file_name_list[500];
while(dp=readdir(dir)) != NULL) {
original_file_name = dp->d_name;
original_file_name_list[counter] = original_file_name;
printf("%s\n",original_file_name_list[0]);
printf("%d\n",counter);
counter++;
}
The problem is, that it prints all files fine. 问题是,它打印所有文件都很好。 It should print only first file, right?
它应该只打印第一个文件,对吗? And if I try
printf("%s\\n",original_file_name_list[1]);
如果我尝试
printf("%s\\n",original_file_name_list[1]);
It doesn't work , which means that it is writing only in 1st string. 它不起作用,这意味着它只在第一个字符串中写入。 Any idea why?
知道为什么吗?
edit: There is no syntax error due to compiler. 编辑:由于编译器没有语法错误。
You're not copying the string at all - also your file_name_list
array hasn't enough space for a list of filenames - just for a list of pointers. 你根本没有复制字符串 - 你的
file_name_list
数组也没有足够的空间容纳文件名列表 - 仅用于指针列表。 But dp->d_name
is just a pointer to a char*
- you can't know for how long the memory behind the pointer is valid. 但是
dp->d_name
只是一个指向char*
的指针 - 你不知道指针后面的内存有多长。 Because of that you have to make a copy for yourself. 因此,你必须为自己制作一份副本。
#include <string.h>
#include <dirent.h>
int main(int argc, char** argv){
char original_file_name_list[50][50];
size_t counter = 0;
while(dp=readdir(dir)) != NULL) // does work fine (ordinary reading files from dir)
{
size_t len = strlen(dp->d_name);
if(len >= 50) len = 49;
strncpy(original_file_name_list[counter], dp->d_name, len);
original_file_name_list[counter][len] = '\0';
printf("%d\n",counter);
counter++;
}
printf("%s\n",original_file_name_list[1]); // <- will work if you have at least 2 files in your directory
return 0;
}
I'm not sure about purpose of counter2
(I have replaced it with counter
) but I can propose the following code with strdup()
call to store the file names: 我不确定
counter2
用途(我用counter
替换它)但是我可以用strdup()
调用来提出以下代码来存储文件名:
char *original_file_name_list[500] = {0}; // it is better to init it here
while(dp=readdir(dir)) != NULL) {
original_file_name_list[counter] = strdup(dp->d_name); // strdup() is ok to use
// here, see the comments
printf("%s\n%d\n",original_file_name_list[counter], counter);
counter++;
}
/* some useful code */
/* don't forget to free the items of list (allocated by strdup(..) )*/
for (int i = 0; i < 500; ++i) {
free(original_file_name_list[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.