0

On running as above the program shows segmentation fault. Why is it so? The program is for pset2 vigenere.c . What I am doing is storing the key in a string and then storing the integer value of key as we used to do in caesar.c and then implementing vigenere cipher but somehow it shows segmentation fault if I compile using make vigenere and then ./vigenere bacon. I am not able to figure out why is it happening.

#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
int main(int argc, string argv[])
{
    if((argc==2)&&(isalpha(argv[1])))
    {
        string k;
        k=argv[1];
        string p = GetString();
        int lenkey=strlen(k);
        int lenp=strlen(p);
        string c="hello";
        char temp;

    //change key to lowercase and store the shift value as in caesar
    for(int i=0;i<lenkey;i++)
    {
        temp=tolower(k[i]);
        k[i]=atoi(c)-'a';

    }
    int j=0;
    for(int i=0;i<lenp;i++)
    {
        //i is for plaintext j is for key
        if(isalpha(p[i]))
        {
            j++;
            if(j==(lenkey-1)) j=0;//reset the key if end is reached
            if(isupper(p[i]))
            {
                p[i] = p[i]-'A';
                c[i] = (p[i]+k[j])%26;
                c[i] = c[i]+'A';
            }
            if(islower(p[i]))
            {
                p[i] = p[i]-'a';
                c[i] = (p[i]+k[j])%26;
                c[i] = c[i]+'a';
            }


        }
        else
            c[i]=p[i];

    }

        printf("%s\n",c);
        return 0;
    }

    else
    {   printf("what?\n");
        return 1;
    }
}
0
isalpha(argv[1])

Is the responsible declaration of segfault, argv[1] is a pointer to a string, isalpha() has as its argument a character. If you do k = argv [1]; you can access each individual character with the notation of array by doing k[0], k[1] etc, in a for loop for example. I hope this helps to get you started.

0

click here to know about salpha()

your is alpha is a function that takes in a character, so to check whether the second argument is right...try to access each character by k1, k[2], so on and check for alphabets. i hope this might help you.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .