您不是 null 终止字符串。这是一个稍微修改的版本:(虽然还是有问题)
#include <stdio.h>
#include <string.h>
int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
int i;
for (i=0; i<strlen(plaintext); i++) {
ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
}
ciphertext_buffer[i] = 0;
return 0;
}
int
main() {
char ciphertext_buffer[11];
encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
printf("%s\n", ciphertext_buffer);
return 0;
}
一个更大的问题是您没有进行任何边界检查。这是一个更好的版本:
#include <stdio.h>
#include <string.h>
int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[], int size) {
int i;
for (i=0; i<strlen(plaintext); i++) {
if (i > size - 1) break;
ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
}
ciphertext_buffer[i] = 0;
return 0;
}
int
main() {
char ciphertext_buffer[11];
encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT", sizeof(ciphertext_buffer));
printf("%s\n", ciphertext_buffer);
return 0;
}