简体   繁体   English

存储指向strsep()的指针返回值

[英]Storing pointers to strsep() return values

When I use strsep() to iterate through the tokens of a string, is it safe for me to store pointers to those tokens, and refer to them later? 当我使用strsep()迭代字符串的标记时,我可以安全地存储指向这些标记的指针,并在以后引用它们吗? Example: 例:

char str[] = "some word tokens";
char *sameStr = str;
char *token, *old1, *old2;

token = strsep(&sameStr, " ");
old1 = token;

token = strsep(&sameStr, " ");
old2 = token;

token = strsep(&sameStr, " ");

printf("%s\n%s\n%s\n", token, old1, old2);

It seems like strsep() always modifies the original character array, inserting null characters after each token. 似乎strsep()总是修改原始字符数组,在每个标记之后插入空字符。 If so, I should be safe storing and later using the old1 and old2 pointers, right? 如果是这样,我应该安全存储,然后使用old1old2指针,对吧? Also, does my use of sameStr cause any problems? 另外,我使用sameStr会导致任何问题吗? I can't use the pointer str directly due to strsep() expecting a restricted char** type. 我不能直接使用指针str ,因为strsep()期望受限制的char **类型。

The stored pointers will be valid until the original string goes out of scope. 存储的指针将有效,直到原始字符串超出范围。 Until then, you can access them however you need to. 在此之前,您可以根据需要访问它们。 The use of sameStr shouldn't cause any problems. 使用sameStr不应该导致任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM