想将非字母字符传递给 C 中的数组但出现分段错误

Want to pass non-alphabetic characters to an array in C but getting a segmentation fault

非常感谢您提供的任何 help/advice!我是菜鸟

该程序应该获取文本并使用用户输入的密钥对其进行加密。因此,当用户使用他们的 26 个字母密钥运行程序时,程序会要求他们提供明文(无论他们想要加密什么),然后程序应该输出密文。我在这个问题中遗漏了验证和附加功能。

=====

我的问题是,在 for 循环中,字母可以正常工作。问题是当存在非字母字符时,程序 returns 出现分段错误。

有谁知道为什么会这样,或者我该如何解决这个问题?与此同时,我会尝试 ctype.h 的“ispunc”“isspace”等。只是想知道是否有其他 BASIC 方法可以比全部输入更短...我们还没有学到指针尚未。

如果需要任何进一步的信息,请告诉我...

// test key: ./substitution JTREKYAVOGDXPSNCUIZLFBMWHQ
// test 2: ./substitution VcHpRzGjNtLsKfBdQwAxEuYmOi
// test 3: ./substitution vchprzgjntlskfbdqwaxeuymoi

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

int validatekey(int argc, string argv[]);
void append(char* s, char c);

int main(int argc, string argv[]) // argc = # of command line args (name of program & input), argv saves them both.
{
    if (validatekey(argc, argv) == 0) //everything is fine
    {
        string key = argv[1]; //user's inputted key
        int keylength = strlen(key);
        string plaintext = get_string("plaintext: ");
        string plainkey = "abcdefghijklmnopqrstuvwxyz";
        int plength = strlen(plaintext);
        char cipher[plength]; //outputted ciphertext

        for (int i = 0; i < plength; i++)
        {
            char p = tolower(plaintext[i]); //make plaintext lowercase so things match up
            char *where_is_p = strchr(plainkey, p);
            int index = (int)(where_is_p - plainkey); // get index of letter in plainkey
            char c = key[index]; //corresponding cipher index location
            
            if (isalpha(plaintext[i])) // check if letter is ALPHABET first
            {
                if (isupper(plaintext[i])) // if current plaintext char is uppercase
                {
                    //append(cipher, toupper(c));
                    printf("is upper");
                }
                else if (islower(plaintext[i])) // if it's lowercase
                {
                    //append(cipher, tolower(c));
                    printf("is lower");
                }
            }
            else //(isalpha(plaintext[i]) == 0 ) // if it's not a-z   NOTE: SEGMENTATION FAULT
            {
                //append(cipher, plaintext[i]);
                printf("not alpha");
            }
        }

        //printf("ciphertext: %s\n", cipher);
    }

}

My question is, in the for loop, alphabetic letters work fine. The issue is when there are NON-ALPHABETIC chars, the program returns a segmentation fault.
Does anyone have any idea why this happens,

strchr(plainkey, p); returns NULLpplainkey 中找不到时。下面的代码死于指针减法和数组索引超出范围。

char *where_is_p = strchr(plainkey, p);
int index = (int)(where_is_p - plainkey);
char c = key[index];

or how I can fix this?

where_is_p == NULL时,执行非字母代码。


顺便说一句,char cipher[plength]; 1 太小,无法形成密文的 字符串