gpt4 book ai didi

将 const char * 复制到 char **

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:53 24 4
gpt4 key购买 nike

我正在使用 libconfig 库从文件中读取一些配置数据。我无法提取用于解析信息和事后清理的功能。

运行 strcpy(*hostname, tmp) 会导致核心转储。

hostnameportip 被初始化为 NULL

int parseConfig(char **hostname, char **port, char **ip) {

config_t cfg, *cf;
const char *tmp;

cf = &cfg;
config_init(cf);

if(!config_read_file(cf, CONFIG)) {
fprintf(stderr, "%s:%d - %s\n",
config_error_file(cf),
config_error_line(cf),
config_error_text(cf));
config_destroy(cf);
return(EXIT_FAILURE);
}

config_lookup_string(cf, "hostname", &tmp);
strcpy(*hostname, tmp);
config_lookup_string(cf, "ip", &tmp);
strcpy(*ip, tmp);
config_lookup_string(cf, "port", &tmp);
strcpy(*port, tmp);

config_destroy(cf);

return(EXIT_SUCCESS);
}

最佳答案

因为它们被初始化为NULL,所以你应该为它们分配足够的内存空间。

config_lookup_string(cf, "hostname",  &tmp);
*hostname = malloc(strlen(tmp)+1);
strcpy(*hostname, tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = malloc(strlen(tmp)+1);
strcpy(*ip, tmp);
config_lookup_string(cf, "port", &tmp);
*port = malloc(strlen(tmp)+1);
strcpy(*port, tmp);

或者,如果您有可用的 strdup()

config_lookup_string(cf, "hostname",  &tmp);
*hostname = strdup(tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = strdup(tmp);
config_lookup_string(cf, "port", &tmp);
*port = strdup(tmp);

关于将 const char * 复制到 char **,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32242740/

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