首页 > 解决方案 > 发布时出现分段错误但调试时很好?cs50数组凯撒赋值

问题描述

我有几个关于分段错误的问题,为什么当我调试我的代码时它很好,但是当它被释放时,分段错误随之而来?我在网上读到它说调试强制代码以正确的顺序运行,因为我正在关注数组的 cs50 课程,我的编码知识就在那里。请提供有关我的代码的一些反馈,我正在尝试寻找改进我非常非常长且不整洁的代码的方法。非常感谢。

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

int main(int argc, string argv[])
{
    if (argc != 2) 
    {
        printf("Usage: ./caesar key\n");
        return -1;
    }
    int n = strlen(argv[1]);
    for (int z = 0; z < n; z++)
    {
        if (isalpha (argv[z]))
        {
            printf("Usage: ./caesar key\n");
        }
    }

    if (argc == 2)
    {    
        {   
            int key = atoi(argv[1]);
            string plaintext = get_string("Plaintext: ");
            int y = strlen(plaintext);
            printf ("Ciphertext: ");
            for (int i = 0; i < y; i++)
            {
                if (key >= 26)
                {
                    printf("%c", (char) plaintext[i] + (key % 26));
                }
                else if (key < 26)
                {
                    printf("%c", (char) plaintext[i] + key);
                }
            }
        }
    }
    return 0; 
}

标签: ccs50

解决方案


推荐阅读