Ant*_*ton 4 c memory arrays strcpy
我将从我目前的代码开始,其中输入是用户提供的变量:
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;
Run Code Online (Sandbox Code Playgroud)
如果我输入"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
Run Code Online (Sandbox Code Playgroud)
我收到的输出如下所示:
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
Run Code Online (Sandbox Code Playgroud)
在我看来,在*strcpy执行期间(strtok_buffer,strtok_result);*next [0]的值被改变了.这令我难以置信.我以前遇到过类似的结果,这与内存重叠(术语?)有关,但我不明白为什么会出现这种情况.
任何帮助表示赞赏,我已经盯着自己盲目地试图解决这个问题.
笔记: