为什么这两个字符数组不能正确连接?(C 编程)


char *program_working_dir;
char backup_dir[9]="/Backups/";
// getting the current working directory
program_working_dir = getcwd(NULL, 0);
if (program_working_dir == NULL){
printf("Failed to get working directory( take_backup function )n");
return -1;
}
// allocate memory for full path that contain the current directory and the /Backups/
char *full_backup_dir = (char *)malloc( (strlen(program_working_dir) + strlen(backup_dir) + 1 ) * sizeof(uint8_t) );
if (full_backup_dir == NULL){
printf("Failed to allocate proper memory to stor full path of backup directoryn");
return -1;
}
// used for debugging purposes
printf("program working dir%sn", program_working_dir); // (here : /home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing/)
printf("%dn",  strlen(program_working_dir));  // ( 86 length of program_working_dir )
// try to concatenate the tow string using snprintf. I add 1 to size for '' terminate string
snprintf(full_backup_dir, ( strlen(program_working_dir) + strlen(backup_dir) +1  ) * sizeof(uint8_t)  , "%s%s", program_working_dir, backup_dir);
printf("Full path: %sn", full_backup_dir);

在这里,我只是试图将两个字符串(路径(连接在一起,但有时我执行这个操作时,它无法正常工作。例如,我得到的是:

program working dir/home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing
86
path /home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing/Backups/��M�X

正如你在这里看到的,在连接之后,我得到了有线字符串/��M�X和这毁了我所有的程序,我不明白为什么会发生这种事。我也尝试使用strncpy和strncat做同样的事情,所以我替换了行:

snprintf(full_backup_dir, ( strlen(program_working_dir) + strlen(backup_dir) +1  ) * sizeof(char)  , "%s%s", program_working_dir, backup_dir);

strcpy(full_backup_dir, program_working_dir);
strcat(full_backup_dir, backup_dir);

仍然有同样的问题。我还删除了我添加到full_back_dir大小的1,但这个程序不想正常运行。在这一点上,我真的很感激任何帮助和反馈。请帮忙!!!!

此阵列

char backup_dir[9]="/Backups/";

不包含字符串,因为它没有足够的空间来存储用作初始值设定项的字符串文字的终止零"\0"。

像一样声明数组

char backup_dir[] = "/Backups/";

事实上,不需要使用函数strlen来计算存储的字符串的长度。它等于sizeof( backup_dir ) - 1

同样在这个表达式中

(strlen(program_working_dir) + strlen(backup_dir) + 1 ) * sizeof(uint8_t)

操作数CCD_ 3是冗余的并且只会混淆代码的读取器。

上面的表达式可以写成

strlen( program_working_dir ) + sizeof( backup_dir )

最新更新