CS50 Caesar程序编译报错:指针与整数的有序比较错误求助
CS50 Caesar密码编译错误及代码修复
编译错误解决
你遇到的ordered comparison between pointer and integer错误,根源是**key被定义为string(即char*指针),但你试图把它当作整数偏移量来计算**。plaintext[j]是单个字符(本质是ASCII整数),和指针类型的key相加、比较属于非法类型操作。
修复步骤:
- 添加头文件
#include <stdlib.h>,这样可以使用atoi()函数把字符串转为整数。 - 把原代码中
string key = argv[1];替换为:int key_int = atoi(argv[1]); - 所有用到
key进行数值计算的地方,都替换成key_int。
代码中的其他致命问题
除了编译错误,你的代码还有两个会导致运行崩溃或结果错误的问题:
1. ciphertext未分配内存
你初始化string ciphertext = NULL;,直接通过ciphertext[j]赋值会触发空指针引用,程序会崩溃。修复:
在获取plaintext之后,为ciphertext分配足够内存:
string plaintext = get_string("plaintext: "); string ciphertext = malloc(strlen(plaintext) + 1); // +1用于存储字符串结束符'\0' if (ciphertext == NULL) { // 检查内存分配是否成功 return 1; }
记得在打印完密文后释放内存:free(ciphertext);
2. 凯撒密码偏移逻辑错误
你当前的if (plaintext[j] + key > z)判断会导致偏移结果错误,比如'Z'加1应该得到'A',但你的计算会得到'B'。正确的循环偏移应该基于字符的基准位置(大写'A',小写'a'):
替换原有的转换代码为:
char base = isupper(plaintext[j]) ? 'A' : 'a'; ciphertext[j] = (plaintext[j] - base + key_int) % 26 + base;
这个公式会自动处理循环偏移,不需要判断是否超过'Z'或'z'。如果需要支持负偏移(比如key为负数),可以再加一行:
if (ciphertext[j] < base) ciphertext[j] += 26;
完整修复代码
#include <cs50.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> int main(int argc, string argv[]) { if (argc != 2) { printf("Usage: ./caesar key\n"); return 1; } string key_str = argv[1]; for (int i = 0; i < strlen(key_str); i++) { if (!isdigit(key_str[i])) { printf("Usage: ./caesar key\n"); return 1; } } int key_int = atoi(key_str); string plaintext = get_string("plaintext: "); string ciphertext = malloc(strlen(plaintext) + 1); if (ciphertext == NULL) { return 1; } for (int j = 0; j < strlen(plaintext); j++) { if (isalpha(plaintext[j])) { char base = isupper(plaintext[j]) ? 'A' : 'a'; ciphertext[j] = (plaintext[j] - base + key_int) % 26 + base; // 处理负偏移情况 if (ciphertext[j] < base) { ciphertext[j] += 26; } } else { ciphertext[j] = plaintext[j]; } } ciphertext[strlen(plaintext)] = '\0'; printf("ciphertext: %s\n", ciphertext); free(ciphertext); return 0; }
内容的提问来源于stack exchange,提问作者user18696024
相关产品推荐
相关产品推荐

