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/