好的,伙计们,这是我在这里的第一篇文章。我的 compsci 课程中最近的作业让我们编写了几个函数来基于简单的偏移量对字符串进行编码和解码。到目前为止,在我的加密函数中,我正在尝试将字符串中的大写字母转换为它们的 ASCII 等价物(一个 int),添加偏移量(并在 ASCII 值超过“Z”时进行调整),将该 int 转换回一个字符(新的加密字符)并将其放入新字符串中。我在这里编译得很好,但是当我运行它并输入简单的大写字符串时,它会给出一个分段错误(核心转储)错误。我在哪里错了?(注意:在尝试解决在 main 中产生一些奇怪错误的情况时,有一些注释掉的位)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//#include <stdlib.h>
char *encrypt(char *str, int offset){
int counter;
char medianstr[strlen(str)];
char *returnstr;// = malloc(sizeof(char) * strlen(str));
for(counter = 0; counter < strlen(str); counter++){
if(isalpha(str[counter]) && isupper(str[counter])){//If the character at current index is an alpha and uppercase
int charASCII = (int)str[counter];//Get ASCII value of character
int newASCII;
if(charASCII+offset <= 90 ){//If the offset won't put it outside of the uppercase range
newASCII = charASCII + offset;//Just add the offset for the new value
medianstr[counter] = (char)newASCII;
}else{
newASCII = 64 + ((charASCII + offset) - 90);//If the offset will put it outside the uppercase range, add the remaining starting at 64(right before A)
medianstr[counter] = (char)newASCII;
}
}
}
strcpy(returnstr, medianstr);
return returnstr;
}
/*
char *decrypt(char *str, int offset){
}
*/
int main(){
char *inputstr;
printf("Please enter the string to be encrypted:");
scanf("%s", inputstr);
char *encryptedstr;
encryptedstr = encrypt(inputstr, 5);
printf("%s", encryptedstr);
//free(encryptedstr);
return 0;
}