C与数组的麻烦,
问题描述:
你好,我是相当新的编程在C和基本上解密数组只有持有的第一个值输入到下面是我的代码还有任何提示,以帮助我提高,我们感激;C与数组的麻烦,
int main(int argc, char *argv[]) {
char input[100] = "";
char target[100] = "";
char replace[100] = "";
char keycipher[100] = "";
int i, size;
static char decrypt[100] = "";
while(1){
printf("\nEnter Target: ");
fgets(target, 17, stdin);
printf("Replace With: ");
fgets(replace, 17, stdin);
for(i = 0; i < size; i++)
{
if(input[i] == target[0]) {
decrypt[i] = target[i];<-this is where it is supposed to be added
input[i] = replace[0];
printf("\n%s",input);
printf("\n%s",decrypt);
}
}
if(target[0] == 'q' || replace[0] == 'q'){
break;
}
}
printf("decryt @# %s", decrypt);
printf("\nDecrypting .....\n");
printf("Your orginal string was: ");
for(i = 0; i < 100; i++)
{
input[i] = decrypt[i];
printf("%s", input);
}
printf("\nSIMULATION OVER!\n");
system("PAUSE");
return 0;
}
我收到的输出如下;
*--------------------------*
| Welcome to the Scrambler |
*--------------------------*
Remember press q to quit
Please enter a string: hello stranger
you entered: hello stranger
Enter target: h
Replace with: w
wello stranger
decrypt array: h
Enter target: s
Replace with: p
wello ptranger
decrypt array: h <-------- why is this still just h?
Enter target: q
Replace with:
decrypt holds: h <----------
Decrypting .....
Your original string was: hello ptrangerhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
SIMULATION OVER!
另外我该如何检查目标是否已经在数组中,以便它们不能添加该字符?
答
的问题是在
char target[0] = "";
char replace[0] = "";
零长度数组不能用于有意义,unless it is the last member of a struct
(柔性阵列构件)。
您需要分配为适用于您的上下文有意义的长度,像
#define LINSIZ 128
char target[LINSIZ ] = "";
char replace[LINSIZ ] = "";
这就是说,你永远不会初始化size
,AO,后来
for(i = 0; i < size; i++)
基本上尝试读取未初始化的自动局部变量的值,它具有不确定的值。它调用调用undefined behavior。
+0
我已经初始化了变量,我只是删除它来尝试减少你读的代码量,它的这个大小=(sizeof input/sizeof input [0]); – Ryan
答
由于您使用的是0长度数组并使用超出边界索引访问它们,因此您的程序受未定义的行为影响。
char target[0] = "";
char replace[0] = "";
看着你的代码,你可能需要它们大到input
。
char target[100] = "";
char replace[100] = "";
decrpyt是什么意思?更精确。 –
'请输入一个字符串:你好,陌生人 你输入了:hello stranger' ...怎么回事? –
用户输入他们交换字符串的字符,我试图将他们的输入保存到数组中,以在完成后用作解密密钥。 – Ryan