gpt4 book ai didi

在遍历同一数组时更改数组值会导致奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-04 05:54:56 24 4
gpt4 key购买 nike

我编写了一个循环,使用引用数组将字符串中的每个字符替换为另一个字符。

for(int i=0 ; i < encoded_message_len ; i++){

for(int j=0; j < 26 ; j++){

if(encoded_message_copy[i] == substitution_alphabet[j]){

printf("%c ->>>> %c @ index:%d \n",encoded_message_copy[i], original_alphabet[j], i);
encoded_message_copy[i] = original_alphabet[j];
}
}
}

然而,当我运行这段代码时,我得到了一个奇怪的输出:

J ->>>> C @ index:0
H ->>>> R @ index:1
Q ->>>> Y @ index:2
Y ->>>> Z @ index:2
S ->>>> P @ index:3
U ->>>> T @ index:4
T ->>>> V @ index:4
X ->>>> O @ index:6
F ->>>> L @ index:7
L ->>>> X @ index:7
X ->>>> O @ index:8
B ->>>> G @ index:9
G ->>>> W @ index:9
Q ->>>> Y @ index:10
Y ->>>> Z @ index:10

当我从循环中删除此行:encoded_message_copy[i] = original_alphabet[j]; 时,我得到了预期的输出:

J ->>>> C @ index:0
H ->>>> R @ index:1
Q ->>>> Y @ index:2
S ->>>> P @ index:3
U ->>>> T @ index:4
X ->>>> O @ index:6
F ->>>> L @ index:7
X ->>>> O @ index:8
B ->>>> G @ index:9
Q ->>>> Y @ index:10

谁能解释为什么会这样?

最佳答案

在需要删除以使其正确的行之后放置一个 break;(在 for 循环内)

你改变了encoded_message_copy的内容,这会导致语句if(encoded_message_copy[i] == substitution_alphabet[j])多次匹配同一个值 ;-)

关于在遍历同一数组时更改数组值会导致奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29807902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com