[英]Function strcpy() changes value of integer array?
我將從我目前的代碼開始,其中輸入是用戶提供的變量:
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]的值被改變了。 這令我難以置信。 我以前遇到過類似的結果,這與內存重疊(術語?)有關,但我不明白為什么會出現這種情況。
任何幫助表示贊賞,我已經盯着自己盲目地試圖解決這個問題。
筆記:
strtok_buffer[2]
不足以容納令牌"A1"
, "B2"
或"C3"
。 不要忘記字符串需要空格來終止空字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.