gpt4 book ai didi

c - 是什么导致出现段错误?

转载 作者:行者123 更新时间:2023-11-30 15:02:20 26 4
gpt4 key购买 nike

按上述方式运行时,程序显示段错误。为什么会这样呢?该程序适用于维吉尼亚密码。我正在做的是将 key 存储在字符串中,然后存储 key 的整数值,就像我们在凯撒密码中所做的那样,然后实现维杰内雷密码,但不知何故,如果我编译它然后使用 ./a.out 它会显示段错误熏肉。我无法弄清楚为什么会发生这种情况(是什么导致了段错误)。

#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
int main(int argc, string argv[])
{
if((argc==2)&&(isalpha(argv[1])))
{
string k;
k=argv[1];
string p = GetString();
int lenkey=strlen(k);
int lenp=strlen(p);
string c="hello";
char temp;

//change key to lowercase and store the shift value as in caesar
for(int i=0;i<lenkey;i++)
{
temp=tolower(k[i]);
k[i]=temp -'a';

}
int j=0;
for(int i=0;i<lenp;i++)
{
//i is for plaintext j is for key
if(isalpha(p[i]))
{
j++;
if(j==(lenkey-1)) j=0;//reset the key if end is reached
if(isupper(p[i]))
{
p[i] = p[i]-'A';
c[i] = (p[i]+k[j])%26;
c[i] = c[i]+'A';
}
if(islower(p[i]))
{
p[i] = p[i]-'a';
c[i] = (p[i]+k[j])%26;
c[i] = c[i]+'a';
}
}
else
c[i]=p[i];
}

printf("%s\n",c);
return 0;
}
else
{ printf("what?\n");
return 1;
}
}

最佳答案

关于atoi :“返回将输入字符解释为数字而生成的 int 值。如果输入无法转换为该类型的值,则返回值为 0。

所以你的atoi(c) -'a'将失败并产生一个负数( c 是字符串“hello”,不能解释为数字)。

您的意思可能是:

        temp=tolower(k[i]);
k[i]=temp -'a';

<小时/>以下也可能是错误:

    for(int i=0;i<lenp;i++) {
...
c[i] = c[i]+'A';

因为i<lenp但它必须小于 c 的长度,即 5。

除此之外,char *c="hello"使 c 成为常量字符串(文字),并且您不能修改文字。因此:段错误。使用:

char c[]="hello";

(所有人,包括老师:放弃那个string!它让每个人都感到困惑!)

关于c - 是什么导致出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41086331/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com