c - 解释我的代码在做什么 (C)

标签 c cstring strcpy

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/

相关文章:

java - JNI 和 UnsatisfiedLinkError

c - 用 C 读取高分/分析字符串

c - strcpy如何改变string的值

c - 字符串数组,C中写入数据失败

c - 从 C 中的函数返回 C 字符串

c++ - 如何将包含空格和数字的句子从大写转换为小写

c - 将 C 字符数组读入 double

使用 strcpy() 函数的正确方法?

C - 将一个字符复制到另一个

c - 进程同步、信号量如何让输出顺序随机?