Cesar encryption using matrices and chars, error in the numbers

0

Here I have the code, basically I have to use the cipher cease in C using matrices and chars only, this is what I have for now:

#include <stdio.h>
#include <stdlib.h>


main ()
{
    char alfabeto[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    int a=0;
    int b=0;
    int m=0;
    int c=0;
    //char letra;
    int cont=0;
    char k[]={};


    printf("Introduzca un primer numero 'a':\n");
    scanf(" %i", &a);
    printf("Introduzca un segundo numero 'b':\n");
    scanf(" %i", &b);

    printf("Introduzca una palabra clave entre 4 y 10 letras (cuando termine presione '.'):\n");    

    //Falta una validacion para la palabra.

        for (int j=0;j<10;j++)
        {
            scanf(" %c",&k[j]);
            cont=j; //cuenta la cantidad de elementos
            if (k[j]=='.')
            {
                j=10;
            }
        }

        for(int j=0;j<cont;j++)
        {
            for (int i=0;i<26;i++)
            {
                if (alfabeto[i]==k[j])
                {
                    m=i;
                    i=26;
                }
            }
                c = ( (a * m) + b );
                printf("%c es: %i \t",k[j],c);
        }
}

Use the formula where c=(a*m+b) .

  • m being the position of the original letter for example: A = 0 then m = 0.

  • a and b being a number to be chosen by the user.

In my case use a=1 and b=3 and CESAR is the keyword.

According to the formula, the value of c for each letter should be:

The result should be:

C is: 5 E is: 7 S is: 21 A is: 3 R is: 20

But it is this in my case:

    
asked by Constanza 31.03.2016 в 22:11
source

1 answer

0

The problem is that you do not dimension the variable k , so the variables you declare in the for end up being "overwritten" when you start to add elements in the array, that breaks all the logic you programmed then the variables have any value and not what you expected.

Remember that in C the memory is administered by you, so if you pass the area of memory assigned to a variable, you are stepping on another variable, especially in function variables that are housed in the stack (or stack).

The solution is to give the variable a size, changing:

char k[]={};

for this other:

char k[14]={0,0,0,0,0,0,0,0,0,0,0,0,0,0};

You could also dynamically allocate memory with the malloc function, but it is not necessary since it is used within the function only.

My Exit:

$ ./a
Introduzca un primer numero 'a':
1
Introduzca un segundo numero 'b':
3
Introduzca una palabra clave entre 4 y 10 letras (cuando termine presione '.'):
CESAR.
C es: 5         E es: 7         S es: 21        A es: 3         R es: 20
    
answered by 31.03.2016 / 22:33
source