简体   繁体   中英

CS50 / BEGINNER - Segmentation fault in nested for loop in C

I'm trying to write code that will take each digit from a plaintext string input and, if it is a letter, output a different letter, as defined by a substitution key (26-letter key).

In other words, if the alphabet was "abcd" and provided key was "hjkl", an input of "bad" would output "jhl".

// Regular alphabet is to be used as comparison base for key indexes //
string alphabet = "abcdefghijklmnopqrstuvwxyz";

// Prompt user for input and assign it to plaintext variable //
string plaintext = get_string("plaintext:  ");

Non-letters should be printed as-is.

My idea was to loop the input digit through every index in the alphabet looking for the corresponding letter and, if found, print the same index character from the string. (confusing, I think)

This loop, however, returns a segfault when I run it, but not when debugging:

// Loop will iterate through every ith digit in plaintext and operate the cipher //
for (int i = 0; plaintext[i] != '\0'; i++) {
    // Storing plaintext digit in n and converting char to string //
    char n[2] = "";
    n[0] = plaintext[i];
    n[1] = '\0';

    // If digit is alphabetic, operate cipher case-sensitive; if not, print as-is //
    if (isalpha(n) != 0) {
        for (int k = 0; alphabet[k] != '\0'; k++) {
            char j[2] = "";
            j[0] = alphabet[k];
            j[1] = '\0';

            if (n[0] == j[0] || n[0] == toupper(j[0])) {
                if (islower(n) != 0) {
                    printf("%c", key[k]);
                    break;
                } else {
                    printf("%c", key[k] + 32);
                    break;
                }
            }
        }
    } else {
        printf("%c", (char) n);
    }
}

What's going wrong? I've looked for help online but most sources are not very beginner-friendly.

Your code seems to be working except one error: The program crashes at

isalpha(n)

Cause you declared

char n[2]

the parameter there is a pointer of type char* . But islower only accepts an int parameter, so just write it as

isalpha(n[0])

Same for islower .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM