-1

I'm new to programming. This is the code as I've written it so far. Disregard the details of the encryption itself; I know that will need more work. When I try to run the program, I get a segmentation fault error message. If argc != 2 I will get the message and if argc == 2 it prints out "keyword" but then it shows the same message and doesn't complete the program, so I think the error has something to do with referincing argv[1].

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

int main (int argc, string argv[])
{
   int i = 0, n = strlen(argv[1]);
   char KeyWord[i]; 

    //makes sure command line has 2 arguements
    if (2 != argc) 

        printf("argc != 2. Try again\n");
        return 1;


    //stores argv[1] as key
    for (i = 0; i < n; i++)
    {
        KeyWord[i] = argv[1][i];  //malloc
        printf("%c", KeyWord[i]);
    }
   printf("\n");

    if (isalpha(KeyWord))
        return 0;
    else
     {   
        printf("try again");
        return 1;
     }

      int j, length;

     printf("input data: ");
     string message = GetString();

     for (i = 0; i < n; i++)   
     {  
        for (j = 0, length = strlen(message); j < length; j++)
        {
            if (islower(message[j]))
            message[j] = message[j] -97 + KeyWord[i];

            if (isupper(message[j]))
            message[j] = message[j] -65 + KeyWord[i];
        }  
        if (i==n) i = 0;
      }  
}
4

1 に答える 1

0

を確認する前strlen(argv[1])に の初期化で計算することはできません。nargc == 2

また、char KeyWord[i]間違っています: iis 0 であるため、何にもスペースを割り当てていません。配列のサイズは 0 よりも大きくなければならないため、コンパイル時に少なくとも警告が表示されるはずです。コメントが示唆する動的割り当てが必要な場合はmalloc、文字列の長さを計算した後に使用する必要があります。

コードは次のようになります。

int i = 0, n;
char *KeyWord; 

// make sure command line has 2 arguments
if (2 != argc) 
{
    printf("argc != 2. Try again\n");
    return 1;
}
n = strlen(argv[1]);
KeyWord = malloc(n+1);
/* ... */
于 2014-01-23T23:51:15.253 に答える