c - getenv() 的值在 strtok() 中不起作用

标签 c char strtok

char *p = strtok (argv[1], ",")    #  Works perfectly
char *p = strtok (getenv("somestring"), ","); # does not work

在我的程序中,我采用 argv[1] 的值,该值以 "x,y" 格式传递 。当未给出 argv[1] 时,我的程序应该从
获取值 getenv("somestring") 也返回 "x,y" 之后我使用 strtok 解析它们。

我不明白为什么 argv[1] 和 getenv() 的行为方式相同,因为如果我没有记错的话,它们的数据类型相同

最佳答案

摘自 getenv 中的注释手册:

As typically implemented, getenv() returns a pointer to a string within the environment list. The caller must take care not to modify this string, since that would change the environment of the process.

strtok 修改字符串时,您必须复制 getenv 返回的字符串,然后使用该副本调用 strtok:

char *str, *ptr;
char *p = getenv("somestring");
str = malloc(strlen(p) + 1);
strcpy(str, p);
ptr = strtok(str, ",");

// Make sure to deallocate the memory once you are done using it.
free(str);

您也可以使用strdup:

char *str, *ptr;
char *p = getenv("somestring");
str = strdup(p);
ptr = strtok(str, ",");

// Make sure to deallocate the memory once you are done using it.
free(str);

关于c - getenv() 的值在 strtok() 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50297854/

相关文章:

c - 函数指针混淆

c - 在c中使用char数组的总线错误

c - 将128分配给c中的char变量

c - 字符串格式、strtok 问题

c - 如何用 C 将莫尔斯码编码为拉丁字母翻译器

c - 使用 time(NULL) 在 C 中创建 Delay() 函数时遇到问题

c - linux:select的第一个参数

C: 函数结束后丢失 char** 的内容

c++ - 使用 strtok() 和 stringstream 的问题

c - strtok() 的问题