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

value of getenv() not working in strtok()

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

在我的程序中,我采用 argv[1] 的值,它以 "x,y" 格式传递 .当没有给出 argv[1] 时,我的程序应该从
中获取值 getenv("somestring") 这也是 returns "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);