首页 > 解决方案 > 谁能告诉我为什么我得到一个分段错误(cs50替换)

问题描述

在我的程序中,我得到了我控制的错误,但是当我试图避免这些预设错误并输入我希望用户输入的内容时,它会返回一个分段错误。

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

int main(int argc, string argv[])
{
    string key = argv[1];
    if (argc < 2 || argc > 2)
    {
        printf("Usage: ./substitution key\n");
        exit(1);
    }
    
    if (argc == 2 && strlen(key) < 26)
    {
        printf("Key must contain 26 characters.\n");
        exit(1);
    }
    
    if (strlen(key) > 26)
    {
        printf("Key must contain 26 characters.\n");
        exit(1);
    }
    
    for (int i = 0; i < 26; i++)
    {
        if (isalpha(key) == 0)
        {
            printf("MAKE SURE YOUR KEY ONLY HAS LETTERS\n");
        }
    }
    printf("test");
}

标签: csegmentation-faultcs50

解决方案


@Retired Ninja 很到位。isalpha on key 导致了分段。这是代码的稍微优化的方式。

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

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        exit(1);
    }
    
    string key = argv[1];
    int keylen = strlen(key);
    
    if (keylen != 26)
    {
        printf("Key must contain 26 characters.\n");
        exit(1);
    } 
    
    for (int i = 0; i < 26; i++)
    {
        unsigned char const c = key[i];
        if (!isalpha(c))
            printf("MAKE SURE YOUR KEY ONLY HAS LETTERS\n");
    }
    printf("test\n");
}

推荐阅读