gpt4 book ai didi

c - 对环境变量进行标记并将生成的标记保存在 char** 中

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

我正在尝试创建一个字符串数组,表示存储在 PATH 变量中的目录。我正在用 C 语言编写此代码,但在使内存分配部分正常工作时遇到问题。

char* shell_path = getenv ("PATH");
char* tok = strtok (shell_path, SHELL_PATH_SEPARATOR);
int number_of_tokens = 0, i = 0;

while (tok != NULL)
{
number_of_tokens++;
}

Shell_Path_Directories = malloc (/* This is where I need some help */);
shell_path = getenv ("PATH");
tok = strtok (shell_path, SHELL_PATH_SEPARATOR);
while (tok != NULL)
{
Shell_Path_Directories[i++] = tok;
tok = strtok (NULL, SHELL_PATH_SEPARATOR);
}

我遇到的问题是我无法想象如何准确知道要分配多少内存。

我知道我对字符串进行了两次标记,而且这样做对我来说可能很愚蠢,但如果有人能找到更好的方法来做到这一点,我愿意接受改进。

最佳答案

只是为了给您提供与 user411313 使用不同方言的基本相同的答案:

char* shell_path = getenv ("PATH");

/* Copy the environment string */
size_t const len = strlen(shell_path)+1;
char *copyenv = memcpy(malloc(len), shell_path, len);

/* start the tokenization */
char *p=strtok(copyenv,SHELL_PATH_SEPARATOR);
/* the path should always contain at least one element */
assert(p);

char **result = malloc(sizeof result[0]);
int i = 0;

while (1)
{
result[i] = strcpy(malloc(strlen(p)+1), p);
p=strtok(0,SHELL_PATH_SEPARATOR);
if (!p) break;
++i;
result = realloc( result, (i+1)*sizeof*result );
}

关于c - 对环境变量进行标记并将生成的标记保存在 char** 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3796660/

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