小编and*_*Fan的帖子

C中的字符串指针可以直接分配字符串文字吗?

以下程序运行正常,我很惊讶为什么:

#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中的字符串分配内存,而我没有分配内存.但是在这种情况下,只需使用""分配字符串值,程序似乎工作正常,任何人都可以解释一下吗?

c string c-strings

3
推荐指数
1
解决办法
136
查看次数

存储文件名在std :: string变量中使用了boost库

我想使用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)

c++ boost boost-filesystem

1
推荐指数
1
解决办法
2617
查看次数

标签 统计

boost ×1

boost-filesystem ×1

c ×1

c++ ×1

c-strings ×1

string ×1