【问题标题】:Segmentation fault (core dumped) when trying to solve problem set尝试解决问题集时出现分段错误(核心已转储)
【发布时间】:2022-12-11 19:55:25
【问题描述】:

我正在尝试解决哈佛 CS50 课程中的 Caesar pset,我认为我基本上是在正确的方法上,但我刚开始收到错误“分段错误(核心已转储)”。

我对编码仍然非常陌生,这就是为什么我在查看其他类似问题时在解决问题时遇到了一些麻烦。也许有人可以看一眼我的代码并提供帮助。

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

char rotate(char c, int n);

int main(int argc, string argv[])
{
    // SAVE CLA AS VARIABLES
    string plaintext = get_string("plaintext: ");
    int key = atoi(argv[1]);
    string cipher = "";
    int length  = strlen(plaintext);

    for (int i = 0; i < length; i++)
    {
        cipher[i] = rotate(plaintext[i], key);
    }

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

char rotate(char c, int n)
{
    //test if c = key is in right range
    c = c + n;

    while (c > 122)
    {
        c = c - 122 + 64;
    }
    return c;
}

【问题讨论】:

  • 第一步应该始终是在调试器中运行您的程序。它将向您显示分段错误发生的位置。您可以检查变量并查找意外值。

标签: c segmentation-fault cs50 coredump


【解决方案1】:

首先,您必须记住stringchar * 的别名。也就是说,string 是一个指针char

那么对于问题:定义

string cipher = "";

使变量cipher 指向空字符串文字。更具体地说,它使 cipher 指向数组的第一个元素,因为所有文字字符串实际上都是字符数组。它是一个只有单个元素的数组,即字符串终止符'

猜你喜欢
  • 1970-01-01
  • 2016-08-18
  • 2021-12-20
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 1970-01-01
相关资源
最近更新 更多