-3

Hello i am fairly new to programming in C and basically the decrypt array only holds the first value entered into in below is my code also any tips to help me improve are appreciated;

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;
}

the output i receive is as follows;

*--------------------------*
| 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!

also how can i check if the target is already in the array so they can`t add that character?

Ryan
  • 25
  • 6

2 Answers2

1

The problem is in

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

zero-length arrays cannot be used meaningfully, unless it is the last member of a struct (a flexible array member).

You need to allocated a meaningful length as applicable in your context, something like

#define LINSIZ 128

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

That said, you never initialized size, ao, later

for(i = 0; i < size; i++)

is essentially trying to read the value of an uninitialized automatic local variable, which has an indeterminate value. It invokes invokes undefined behavior.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • i have initialized the variable i just removed it to try reduce the amount of code you guys read through, its this size = (sizeof input / sizeof input[0]); – Ryan Feb 19 '16 at 16:59
0

Your program is subject to undefined behavior since you are using 0 length arrays and accessing them using out of bounds indices.

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

Looking at your code, you probably need them to be as large as input.

char target[100] = "";
char replace[100] = "";
R Sahu
  • 204,454
  • 14
  • 159
  • 270