【问题标题】:Function strcpy() changes value of integer array?函数 strcpy() 改变整数数组的值?
【发布时间】:2014-02-04 11:22:35
【问题描述】:

我将从我目前拥有的代码开始,其中 input 是用户提供的变量:

int current[2] = {-1, -1}, next[2] = {-1, -1};
char *strtok_result = strtok(input, " ");
int i = 0;
while(strtok_result != NULL){
    i++;
    int count = 0;
    char strtok_buffer[2];
    printf("iteration %d-%d: next[0] = %d\n", i, ++count, next[0]);
    strcpy(strtok_buffer, strtok_result);
    printf("iteration %d-%d: next[0] = %d\n", i, ++count, next[0]);

    current[0] = next[0];
    current[1] = next[1];
    next[0] = strtok_buffer[1] - 48;            // ascii conversion, digit to column
    next[1] = toupper(strtok_buffer[0]) - 64;   // --- || ---, letter to row
    printf("iteration %d-%d: next[0] = %d\n\n", i, ++count, next[0]);
    strtok_result = strtok(NULL, " ");
}
return 0;

如果我输入“A1 B2 C3”,我希望得到以下输出:

iteration 1-1: next[0] = -1
iteration 1-2: next[0] = -1
iteration 1-3: next[0] = 1

iteration 2-1: next[0] = 1
iteration 2-2: next[0] = 1
iteration 2-3: next[0] = 2

iteration 3-1: next[0] = 2
iteration 3-2: next[0] = 2
iteration 3-3: next[0] = 3

我收到的输出如下所示:

iteration 1-1: next[0] = -1
iteration 1-2: next[0] = -256
iteration 1-3: next[0] = 1

iteration 2-1: next[0] = 1
iteration 2-2: next[0] = 0
iteration 2-3: next[0] = 2

iteration 3-1: next[0] = 2
iteration 3-2: next[0] = 0
iteration 3-3: next[0] = 3

在我看来,在执行 *strcpy(strtok_buffer, strtok_result);* 期间,next[0] 的值被改变了。这让我感到困惑。我之前遇到过类似的结果,这与内存重叠(术语?)有关,但我不明白为什么会在这里发生。

感谢任何帮助,我一直盯着自己试图弄清楚这一点。

注意事项:

  • 已确认输入采用“XY XY ...”格式,其中 X 是字母,Y 是数字。
  • current[0]、current[1] 和 next[1] 不会以任何方式改变。我决定排除这些输出,这样您就不必查看 2x36 行的数字。

【问题讨论】:

  • strcpy 复制以 null 结尾的字符串 plus。因此,要复制“A1”,您的strtok_buffer 缓冲区中至少需要 3 个字节,而不是 2 个。
  • 哇,我该休息一下了。我刚刚意识到它必须是 3 号。试了一下,它工作正常。好的,谢谢!
  • 查看汇编代码并查看编译器将next 相对于strtok_buffer 放在哪里。 “内存重叠(术语?)”——您想要的术语是“缓冲区溢出”。希望从这次经历中你永远不会再被这个困惑,并且永远对 strcpy 保持警惕。

标签: c arrays memory strcpy


【解决方案1】:

strtok_buffer[2] 不够大,无法容纳标记 "A1""B2""C3"。不要忘记字符串需要用于终止空字符的空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2020-05-16
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多