【问题标题】:explanation of what my code is doing (C)解释我的代码在做什么 (C)
【发布时间】:2013-11-03 02:02:33
【问题描述】:
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 将从我的程序中删除。我只是用它来展示我的程序发生了什么。

有人可以向我解释发生了什么吗?谢谢。

【问题讨论】:

  • 您似乎在混合使用strtempsubString,以及它们的用途。

标签: c cstring strcpy


【解决方案1】:

重要的是要意识到strtok() 会就地修改源字符串,并返回指向它的指针。

因此,对strtok() 的两次调用将str 变为

#include \0hello.txt\0
           ^ subString points here

(为简单起见,我没有显示最终终止\0)。

现在,第二个(“有问题的”)strcpy()str 改回:

#include "hello.txt"
          ^ subString still points here

这就是" 重新出现在subString 中的原因。

修复它的一种方法是对副本进行标记并保持原件完好无损。只需确保您的函数不返回指向自动变量的指针(该变量会在函数返回时超出范围)。

【讨论】:

  • 哇,谢谢。我知道如何解决它。我只是想了解它为什么会这样做。我只是对 temp 变量进行了标记,因为我希望原始参数保持不变。这很有意义。再次感谢。
【解决方案2】:

首先要知道strtok修改了第一个参数(str),如果这是一个常量(比如调用extractSubstring时像这样:extractSubstring("#include \"hello.txt\"");)那么这会导致未定义的行为

您已经将str 复制到temp,因此您应该在调用strtok 时使用temp。标记化完成后,您应该将subString 复制到您在堆上分配的变量(malloc)或作为额外参数传递给extractSubstring。您不能返回指向本地数组的指针,因为该数组超出了函数结束的范围。

总之:

subString = strtok(temp, "\"");
subString = strtok(NULL, "\"");

char * ret = malloc(strlen(subString));
strcpy(ret, subString);
ret[strlen(ret)] = '\0';

return ret;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2015-07-08
    • 2015-01-16
    • 2021-04-07
    相关资源
    最近更新 更多