【发布时间】:2017-07-26 05:34:29
【问题描述】:
请耐心等待我的代码。我是 C 的初学者。下面的代码构建了一个 Vigenere 密码。用户输入用于加密plaintext 消息的key 参数。代码将输出ciphertext。
我收到的错误如下。请注意,我还没有研究过指针。
我们将不胜感激任何诊断错误的帮助!
vigenere.c:47:13: runtime error: store to null pointer of type 'char'
Segmentation fault
代码
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[]){
// check for 2 arguments
if (argc != 2){
printf("missing command-line argument\n");
return 1;
}
// check for character argument
int i,n;
for (i = 0, n = strlen(argv[1]); i < n; i++){
if (!isalpha(argv[1][i])){
printf("non-character argument\n");
return 1;
}
}
// if previous 2 checks are cleared, request 'plaintext' from user
printf("plaintext:");
// declare plaintext, key, and ciphertext
string t = get_string(); // plaintext
string u = argv[1]; // key (argument)
string y = NULL; // ciphertext
// encode plaintext with key -> ciphertext
for (i = 0, n = strlen(t); i < n; i++){
if (tolower(t[i])){
y[i] = (char)((((int)t[i] + (int)tolower(u[i%n])) - 97) % 26) + 97;
} else {
y[i] = (char)((((int)t[i] + (int)tolower(u[i%n])) - 65) % 26) + 65;
}
}
printf("ciphertext: %s\n", y);
}
【问题讨论】:
-
您尝试取消引用空指针并写入它?这应该很清楚。如果你不知道指针,那你为什么要使用它们呢? Get a couple of good beginners books 并阅读。先学后用。
-
string y = NULL;-->string y = calloc(strlen(t)+1, sizeof(char)); -
在不相关的注释上,请避免使用magic numbers。如果
97是指ASCII 字符'a',那么say 就是这样。或者更好的是,因为你想在大写和情人之间转换使用toupper和tolower。您已经使用了toupper,但错误的是,您应该改用isupper。 -
关于指针,类型名称
string是char *的别名。它是一种指针类型。这是 CS50 及其库的坏处之一,它让您相信实际上您没有使用指针。虽然 CS50 库确实隐藏了 C 的一些复杂性,但这样做不利于在 IMO 中正确学习 C。 -
if (tolower(t[i])){-->if (islower((unsigned char)t[i])){
标签: c pointers encryption segmentation-fault cs50