C阵列有问题,

时间:2016-02-19 16:25:45

标签: c arrays

您好,我在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!

我如何检查目标是否已经在数组中,以便他们不能添加该字符?

2 个答案:

答案 0 :(得分:1)

问题在于

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

答案 1 :(得分:0)

您的程序受到未定义的行为,因为您正在使用0个长度数组并使用越界索引访问它们。

char target[0] = "";
char replace[0] = "";

查看代码,您可能需要它们与input一样大。

char target[100] = "";
char replace[100] = "";