gpt4 book ai didi

c - 将 getcwd 存储在函数的结构上

转载 作者:行者123 更新时间:2023-11-30 20:35:49 25 4
gpt4 key购买 nike

typedef struct 
{
char Path[100];
} DirectoryInformation;

void Getskelutofdirectorie(char * dir, int lvl)
{
DirectoryInformation DI[100];
char cwd[1024];

//Search recursive

// where I want to put the path on the struct to use on main

getcwd(cwd, sizeof(cwd));
strcpy(DI[0].Path, cwd);
}

int main(void)
{
DirecoryInformation DI[100];
printf("%s", DI[0].Path);

}

我可以打印路径,但如果我在主函数上使用就可以了。

有人可以帮我吗?

它执行时没有错误,但是当我打印出来时出现段错误

最佳答案

您的代码通过使用具有自动存储持续时间且未初始化(不确定)的变量DI 的值来调用未定义的行为

调用函数并传递指向结构的指针来存储数据,然后存储在那里。

typedef struct
{
char Path[100];
} DirectoryInformation;

void Getskelutofdirectorie(DirectoryInformation * DI, char * dir, int lvl)
{
char cwd[100]; // cwd was too long, so there was risk of buffer overrun when copying

//Search recursive

//where i want to put the path on the struct to use on main

getcwd(cwd, sizeof(cwd));
strcpy(DI[0].Path, cwd);
}

int main(void)
{
DirectoryInformation DI[100] = {{""}}; // initialize for in case the function fails to set values
Getskelutofdirectorie(DI, NULL, 0); // pass proper parameter
printf("%s", DI[0].Path);

}

关于c - 将 getcwd 存储在函数的结构上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37714083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com