char *extractSubstring(char *str)
{
char temp[256];
char *subString; // the "result"
printf("%s\n", str); //prints #include "hello.txt"
strcpy(temp, str); //copies string before tokenizing
subString = strtok(str,"\""); // find the first double quote
subString = strtok(NULL,"\""); // find the second double quote
printf("%s\n", subString); //prints hello.txt
strcpy(str, temp); //<---- the problem
printf("%s", subString); //prints hello.txt"
return subString;
}
为什么我在strcpy之后加了引号?当我注释掉第二个 strcpy 行时,程序运行。 printfs 将从我的程序中删除。我只是用它来展示我的程序发生了什么。
谁能给我解释一下这是怎么回事?谢谢。
最佳答案
重要的是要意识到 strtok()
就地修改源字符串,并返回指向它的指针。
因此,对strtok()
的两次调用将str
变成了
#include \0hello.txt\0
^ subString points here
(为简单起见,我没有显示最终终止 \0
)。
现在,第二个(“有问题的”)strcpy()
将 str
改回:
#include "hello.txt"
^ subString still points here
这就是 "
重新出现在 subString
中的原因。
修复它的一种方法是标记副本并保持原件完好无损。只需确保您的函数不会返回指向自动变量的指针(在函数返回时会超出范围)。
关于c - 解释我的代码在做什么 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19564656/