以下程序运行正常,我很惊讶为什么:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void xyz(char **value)
{
// *value = strdup("abc");
*value = "abc"; // <-- ??????????
}
int main(void)
{
char *s1;
xyz(&s1);
printf("s1 : %s \n", s1);
}
Run Code Online (Sandbox Code Playgroud)
输出:
s1 : abc
Run Code Online (Sandbox Code Playgroud)
我的理解是我必须使用strdup()函数为C中的字符串分配内存,而我没有分配内存.但是在这种情况下,只需使用""分配字符串值,程序似乎工作正常,任何人都可以解释一下吗?
我想使用boost :: filesystem获取目录中所有文件的列表
我能够使用打印文件名,cout但我无法将文件名存储在字符串变量中.我也尝试过类型转换和strcpy,但没有一种方法可行.
以下是代码:
char dir[100] = "/home/harsh/";
namespace fs = boost::filesystem;
fs::directory_iterator start = fs::directory_iterator(dir);
fs::directory_iterator di = start;
for (; di != fs::directory_iterator(); ++di)
{
std::cout << "hello .. " << di->path() << std::endl;
//std::string strHarsh = di->path(); //Error
}
Run Code Online (Sandbox Code Playgroud)