0

Goodmorning,

My program compiles, but when I try to run it with only the name of the program 'vigenere', I get this.
"vigenere.c:12:23: runtime error: load of null pointer of type 'char' Segmentation fault."

Here is my code:

#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, string argv[])
{
    string k = argv[1];
    string s;
    int i, index =0;
    while (!(argc = 2 && isalpha(k[index])))
    {
        printf("only the program name and an alphabetical keyword\n");
        return 1;
    }

    s = get_string("plaintext:  ");
    printf("ciphertext:  ");

    int n;
    for (i = 0, n = strlen(s); i < n; i++)
    {
        if (islower(s[i]))
        {
            printf("%c", (s[i] - 97 + toupper(k[index])% 26 + 97));
            index = (index + 1)% n;
        }
        else if (isupper(s[i]))
        {
            printf("%c", (s[i] - 65 + (k[index]% 26 + 65)));
            index = (index + 1)% n;
        }
        else
        {
            printf("%c", s[i]);
        }
    }
    printf("\n");
    return 0;
}
0

If you run the program with no parameters, argc = 1 and argv[1] doesn't exist. Now, look at this line:

string k = argv[1];

Since argv[1] doesn't exist, this line throws an error. Any further lines that use an element from the argv array, other than argv[0], will produce an error too.

That's why the first thing to do is check the value of argc and make sure there are enough arguments. (argc stands for argument count.)

The while loop should have come before the assignment statement. Also, that should be an if statement, not a while loop. There's no looping to be done. It either is or isn't the right number of parameters.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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